Show in Html a JSON file in Angular - html

I'm trying to print a JSON (link to the JSON) in an html file.
JSON:
{
"ricette": {
"FRIGGITRICI": {
"Alici": [
[
{"500": "scongelamento"}
],
[
{"60": "nada"}
]
],
"BaccalĂ ": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
},
"GRIGLIA": {
"BaccalĂ ": [
[
{"500": "scongelamento"}
],
[
{"210": "immerso"},
{"210": "cestello su"},
{"30": "immerso"}
]
]
}
}
}
I've fetched it and saved in a variable:
export class DatiService {
fileJson: JSON;
constructor() { }
private datiUrl = 'https://api.myjson.com/bins/zbfh5';
async getDati(){
await fetch(this.datiUrl)
.then(res => res.json())
.then((out) => {
this.fileJson=out;
});
console.log(this.fileJson);
};
}
How can i print it in the html code?
Can i just use de "." to enter in its fields?
Or it's more complicated?

You can use the JsonPipe in your template.
{{fileJson | json}}
If you want to print a specific part you can navigate via . deeper into the object structure.
{{fileJson.ricette.FRIGGITRICI | json}}
If you want to print a primitiv value interpolation is enough and no json pipe is needed.
{{fileJson.version}}
UPDATE
Did you called your getDati function? Add an ngOnInit Lifecycle Hook and call it there. Here is an working stackblitz sample.
I just realized it's a service in your sample code. Take the service and inject it into a component and call it there.

We can use pre tag to view JSON data in HTML
Pass your JSON in var data.
And Set pre tag in HTML body.
var data = {Your JSON Object}
$("#json").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="json"></pre>

Related

JSON object has values, but they're empty

This is JSON 101 but I don't understand what i'm doing wrong.
This is for a discord.js bot, where a command has client passed to it. The client exists and provides all of the data that I would expect to see. The problem is that I then do not have access to the guilds or channel ids
Code:
module.exports = {
name: 'command',
execute(client) {
console.log(JSON.stringify(client))
console.log(JSON.stringify(client.guilds))
console.log(JSON.stringify(client.channels))
}
}
My response (reduced for "easier" reading):
{
"guilds": [
"00101010101010101"
],
"channels": [
"101010101010101010",
"101010011010101010"
]
}
{}
{}

Iterate through nested JSON in React JS

I am having trouble finding a way to iterate through this JSON file. The JSON is acquired after calling an API.
I would like to use this JSON for mapping and create components from it.
Problem: How do I navigate through nested JSON and map it?
JSON Format
The JSON format that i received is just as below. I cannot change the file as it is called from an API.
{"animals":{
"dogs":{
"name": "rex", (required)
"breed": "yorkshire"}
"cats":{
"name": "tom", (required)
"breed": "sphinx"}
}
}
Goal
Since mapping can be done in an array of objects, the ideal case would be [{dogs},{cats}].
var json = *serializableJSONFormat*
json.map((item)=>{
<MenuItem value={item.name}>{item.name}</MenuItem>
})
Assuming your JSON is structured like
{"animals":{
"dogs": [
{
"name": "rex",
"breed": "yorkshire"
}
],
"cats":[
{
"name": "tom",
"breed": "sphinx"
}
]
}
(And therefore assuming that every key has an array as value.)
You can loop over all keys and map the arrays
menuItems = [];
animals = YOUR_JSON["animals"];
Object.keys(animals).forEach((key) => {
menuItems = menuItems.concat(animals[key].map((item)=>{
<MenuItem value={item.name}>{item.name}</MenuItem>
}));
}
Perhaps you would like something like this:
Object.keys(json["animals"]).map(key => {
return (
<MenuItem
value={json["animals"][key]["name"]}
>
{json["animals"][key]["name"]}
</MenuItem>
)
})
But as the comments on our questions said, it'd be easier if the "animals" property was an array instead.

Retrieve values from JSON response, and create a drop-down

I'm trying to get each of of the values inside my JSON file but when I run my API I get [Object Object] instead of what is inside the JSON.
This is my API request:
getAllvalues(): Observable<string[]> {
return this.http
.get<string[]>(this.Url + 'api');
}
my component.ts
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
console.log (this.slots)
});
Example of my JSON response:
[
{
"AB": "http:"
},
{
"DE": "http:"
},
{
"CE": "http:"
},
{
"HI": "http:"
}
]
How can I get the value inside the JSON, and create a dropdown box with each of them?
Your example JSON is a pretty bad example: each object in the array in the JSON should have at least somewhat matching key names. In your case, the keys are "AB", "DE", "CE", "HI" - all different, which is quite uncommon in real-life. A more realistic JSON response would have matching key names, e.g.:
[
{
"id": "1",
"description": "Some description"
},
{
"id": "2",
"description": "Another description"
}
]
Now to answer your questions:
You are getting [Object Object] because you are trying to use an entire object as a literal value. Instead, you should access the individual keys/values of an object. For example: console.log(slots[0].id) - this should output 1.
Also, as indicated in the comments, replace Observable<string[]> with Observable<any[]> and get<string[]> with get<any[]>.
To create a drop-down in Angular, in your component template you can try this, assuming your slots value is the JSON above:
<select *ngIf="slots" name="slots">
<option *ngFor="let slot of slots" value="slot.id">{{ slot.description }}</option>
</select>
Also, to print the entire object to console in a readable form, instead of just console.log(this.slots);, you can try console.log(JSON.stringify(this.slots));
As mentioned in the comments above it is not ideal to have json like you have, my assumption is you might want to log keys instead of values, since value is same for all the objects in array. In that case you might want to try something like this.
1. Add any[] instead string[].
2.Add nested for loop to console.log your object array.
getAllvalues(): Observable<string[]> {
return this.http
.get<any[]>(this.Url + 'api');
}
this.ddvService.getAllvalues()
.subscribe(response => {
this.slots = response;
for(let i in this.slots)
{
let currentObj = this.slots[i]; // example of first in array { AB : "http:"}
for ( let z in currentObj )
{
if(currentObj[z]=== "http:") // we are trying to find key instead value
{
console.log(z); // it will log AB, DE, CE, HI ..
}
}
}
});

Plotting JSON data with angular2-highchart

I want to plot data in a JSON file using angular2-highcharts.
Let's say there are X and Y values in the JSON file in the following format:
[[[1,15],[2,16],[3,18]]]. The code is as follows.
#Component({
selector: 'my-app',
directives: [CHART_DIRECTIVES],
template:`{{sample}}
<center> <chart [options]="options"></chart></center>`
})
export class AppComponent {
public sample;
options:Object;
constructor(public http : Http) {
http.get('data.json')
.map(res => res.json())
.subscribe(data =>this.sample=JSON.parse(JSON.stringify(data || null)),
err=>console.log(err),
() => console.log('Completed')); {}
console.log(this.sample);
this.options = {
title : { text : 'Sample Curve' },
series: [
{ data: this.sample,
color:'red'},]
}
}
}
I get the values of data in the .json file and display it as a part of the template and the correct values seem to get printed. However, my highchart plot is empty. Since i am equally new to Javascript and typescript, I probably am not making full use of some answers here already.
You are trying to implement simple line chart.
Line Chart expects data to be in this formats-
[29.9, 71.5, 106.4, 129.2] or [[1,15],[2,16],[3,18]]
whereas your json structure is in this format
[[[1,15],[2,16],[3,18]]]
You can try like this-
Import JSONP_PROVIDERS-
import {JSONP_PROVIDERS, Jsonp} from '#angular/http';
providers: [JSONP_PROVIDERS],
In html template-
<chart [options]="options1"></chart>
In your component-
options1: Object;
constructor(jsonp : Jsonp) {
jsonp.request('https://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=JSONP_CALLBACK').subscribe(res => {
this.options1 = {
title : { text : 'AAPL Stock Price' },
series : [{
name : 'AAPL',
data : res.json(),
tooltip: {
valueDecimals: 2
}
}]
};
});
See if this helps.
Okay, so, the options for the chart component needs to be set within the subscribe method as in the above example Sanket has posted. I was not giving it within subscribe. The value stored in this.sample goes back to what it was initialized to once outside the subscribe method.I still don't understand why the values get printed correctly in the template portion though.

Changing the labels jsonBuilder creates automatically in Groovy after converting Obj to JSON

I have a class called Case which is like:
class Case {
String caseId;
Map <String, List<String[]>> listOfCases = new HashMap<String, ArrayList<String[]>>();
}
I created several of these cases and add them to a list. Eventually I want to print the list in JSON format in groovy like:
for (...){
// creating many of these cases in a loop and adding to caseList
caseList.add(myCase);
}
// Finally printing them
println new JsonBuilder( caseList ).toPrettyString()
Result looks like this, I chose one only:
{
"caseId": "Case_1",
"listOfCases": {
"server-config.xml": [
[
"Core",
"8"
]
],
"server-beans.xml": [
[
"plugin",
"mmap"
],
[
"maxIdle",
"16"
],
[
"minIdle",
"16"
],
[
"maxCon",
"16"
]
]
}
}
I want the listOfCases be replaced with Case_1 so each time I create a new Case with the number incremented, the name follows. Is there anyway to customize the jsonBuilder in groovy to do this ?
As stated in How to modify JSON in groovy changing the content is dangerous, as it attempts to change the original object. The solution presented there is to send the proper map.
You can prepare a map from your data and pass this like this:
class Case {
String caseId
Map<String,List<List<String>>> listOfCases
}
def caseList = (1..3).collect{
new Case(caseId: "Case$it", listOfCases: [ 'abcde': [['1','2'],['4','5']]])
}
println new groovy.json.JsonBuilder(caseList.collect{[caseId: it.caseId, "$it.caseId": it.listOfCases]}).toPrettyString()
results in
[
{
"caseId": "Case1",
"Case1": {
"abcde": [
...