How to do ngFor loop on nested json object? - json
It seems to be simple thing to do, but somehow i did not get inner array element to do ngFor loop on Angular 2.
I have json array as below, and i need to iterate through available 'routes' in my response array which is nested element.
Now can any one let me know how can i get route which should be simple and i am trying like this.routes=respondeJson[0].routes Or this.routes=resonseJson[0]['routes'] but no luck. Please help considering my entry level here on Angular 2 or say working with JSON.
[
{
"routes": {
"0": {
"budget": 326,
"toCity": "United States",
"QuoteIds": [
1,
2
],
"options": 2
},
"1": {
"budget": 374,
"toCity": "Thailand",
"QuoteIds": [
3,
4
],
"options": 2
},
"2": {
"budget": 382,
"toCity": "Singapore",
"QuoteIds": [
5,
6
],
"options": 2
},
"3": {
"budget": 451,
"toCity": "Taiwan",
"QuoteIds": [
7
],
"options": 1
},
"5": {
"budget": 112,
"toCity": "Turkey",
"QuoteIds": [
8
],
"options": 1
},
"6": {
"budget": 314,
"toCity": "Saudi Arabia",
"QuoteIds": [
9
],
"options": 1
},
"8": {
"budget": 518,
"toCity": "Indonesia",
"QuoteIds": [
10
],
"options": 1
},
"10": {
"budget": 384,
"toCity": "Hong Kong",
"QuoteIds": [
11,
12
],
"options": 2
},
"11": {
"budget": 232,
"toCity": "Qatar",
"QuoteIds": [
13
],
"options": 1
},
"22": {
"budget": 254,
"toCity": "Algeria",
"QuoteIds": [
14
],
"options": 1
},
"23": {
"budget": 241,
"toCity": "Kuwait",
"QuoteIds": [
15
],
"options": 1
},
"24": {
"budget": 175,
"toCity": "Israel",
"QuoteIds": [
16,
17
],
"options": 2
},
"25": {
"budget": 266,
"toCity": "Oman",
"QuoteIds": [
18,
19
],
"options": 2
},
"28": {
"budget": 762,
"toCity": "Argentina",
"QuoteIds": [
20,
21
],
"options": 2
},
"30": {
"budget": 78,
"toCity": "Iceland",
"QuoteIds": [
22
],
"options": 1
},
"37": {
"budget": 327,
"toCity": "Canada",
"QuoteIds": [
23,
24
],
"options": 2
},
"39": {
"budget": 238,
"toCity": "Iran",
"QuoteIds": [
25
],
"options": 1
},
"40": {
"budget": 129,
"toCity": "Cyprus",
"QuoteIds": [
26
],
"options": 1
},
"41": {
"budget": 267,
"toCity": "United Arab Emirates",
"QuoteIds": [
27,
28
],
"options": 2
},
"42": {
"budget": 252,
"toCity": "Lebanon",
"QuoteIds": [
29
],
"options": 1
},
"43": {
"budget": 427,
"toCity": "Iraq",
"QuoteIds": [
30
],
"options": 1
},
"50": {
"budget": 142,
"toCity": "Montenegro",
"QuoteIds": [
31
],
"options": 1
},
"55": {
"budget": 418,
"toCity": "Cuba",
"QuoteIds": [
32
],
"options": 1
},
"56": {
"budget": 492,
"toCity": "China",
"QuoteIds": [
33,
34
],
"options": 2
},
"57": {
"budget": 444,
"toCity": "India",
"QuoteIds": [
35
],
"options": 1
},
"62": {
"budget": 477,
"toCity": "Japan",
"QuoteIds": [
36,
37
],
"options": 2
},
"63": {
"budget": 3377,
"toCity": "Costa Rica",
"QuoteIds": [
38
],
"options": 1
},
"65": {
"budget": 210,
"toCity": "Georgia",
"QuoteIds": [
39
],
"options": 1
},
"66": {
"budget": 391,
"toCity": "Sri Lanka",
"QuoteIds": [
40,
41
],
"options": 2
},
"67": {
"budget": 258,
"toCity": "Russia",
"QuoteIds": [
42
],
"options": 1
},
"68": {
"budget": 82,
"toCity": "Poland",
"QuoteIds": [
43
],
"options": 1
},
"71": {
"budget": 104,
"toCity": "Finland",
"QuoteIds": [
44
],
"options": 1
},
"72": {
"budget": 150,
"toCity": "Austria",
"QuoteIds": [
45,
46
],
"options": 2
},
"73": {
"budget": 68,
"toCity": "Spain",
"QuoteIds": [
47
],
"options": 1
},
"75": {
"budget": 106,
"toCity": "Portugal",
"QuoteIds": [
48
],
"options": 1
},
"77": {
"budget": 37,
"toCity": "Romania",
"QuoteIds": [
49
],
"options": 1
},
"78": {
"budget": 66,
"toCity": "Sweden",
"QuoteIds": [
50
],
"options": 1
},
"79": {
"budget": 77,
"toCity": "Denmark",
"QuoteIds": [
51
],
"options": 1
},
"86": {
"budget": 440,
"toCity": "South Africa",
"QuoteIds": [
52,
53
],
"options": 2
},
"87": {
"budget": 176,
"toCity": "Morocco",
"QuoteIds": [
54,
55
],
"options": 2
},
"88": {
"budget": 231,
"toCity": "Serbia",
"QuoteIds": [
56
],
"options": 1
},
"89": {
"budget": 279,
"toCity": "Bosnia and Herzegovina",
"QuoteIds": [
57
],
"options": 1
},
"90": {
"budget": 35,
"toCity": "Italy",
"QuoteIds": [
58
],
"options": 1
},
"92": {
"budget": 72,
"toCity": "Hungary",
"QuoteIds": [
59
],
"options": 1
},
"93": {
"budget": 155,
"toCity": "Croatia",
"QuoteIds": [
60
],
"options": 1
},
"94": {
"budget": 160,
"toCity": "Malta",
"QuoteIds": [
61,
62
],
"options": 2
},
"95": {
"budget": 163,
"toCity": "Greece",
"QuoteIds": [
63,
64
],
"options": 2
},
"96": {
"budget": 67,
"toCity": "Ireland",
"QuoteIds": [
65
],
"options": 1
},
"97": {
"budget": 60,
"toCity": "Netherlands",
"QuoteIds": [
66
],
"options": 1
},
"98": {
"budget": 68,
"toCity": "Norway",
"QuoteIds": [
67
],
"options": 1
},
"99": {
"budget": 71,
"toCity": "Latvia",
"QuoteIds": [
68
],
"options": 1
},
"100": {
"budget": 261,
"toCity": "Belgium",
"QuoteIds": [
69
],
"options": 1
},
"101": {
"budget": 60,
"toCity": "Bulgaria",
"QuoteIds": [
70
],
"options": 1
},
"102": {
"budget": 130,
"toCity": "Switzerland",
"QuoteIds": [
71
],
"options": 1
},
"103": {
"budget": 140,
"toCity": "Ukraine",
"QuoteIds": [
72
],
"options": 1
},
"104": {
"budget": 72,
"toCity": "France",
"QuoteIds": [
73
],
"options": 1
},
"105": {
"budget": 56,
"toCity": "Lithuania",
"QuoteIds": [
74
],
"options": 1
},
"106": {
"budget": 51,
"toCity": "United Kingdom",
"QuoteIds": [
75
],
"options": 1
},
"109": {
"budget": 116,
"toCity": "Czech Republic",
"QuoteIds": [
76
],
"options": 1
},
"110": {
"budget": 59,
"toCity": "Germany",
"QuoteIds": [
77
],
"options": 1
},
"113": {
"budget": 272,
"toCity": "Bahrain",
"QuoteIds": [
78,
79
],
"options": 2
},
"128": {
"budget": 634,
"toCity": "New Zealand",
"QuoteIds": [
80
],
"options": 1
},
"147": {
"budget": 610,
"toCity": "Australia",
"QuoteIds": [
81
],
"options": 1
},
"167": {
"budget": 187,
"toCity": "Moldova",
"QuoteIds": [
82
],
"options": 1
},
"168": {
"budget": 87,
"toCity": "Slovakia",
"QuoteIds": [
83
],
"options": 1
},
"175": {
"budget": 119,
"toCity": "Gibraltar",
"QuoteIds": [
84
],
"options": 1
},
"178": {
"budget": 545,
"toCity": "Laos",
"QuoteIds": [
85
],
"options": 1
}
},
"misc": {
"QuoteDateTime": "2017-04-21T13:56:00",
"MinPrice": 326,
"Direct": false,
"QuoteId": 1,
"skyLink": "http://partners.api.skyscanner.net/apiservices/referral/v1.0/AU/AUD/en-US/anywhere/amd/2017-05-18/2017-05-22?apiKey=wc161029621991497683276175998396"
},
"price": [
326,
392,
374,
434,
382,
470,
451,
112,
314,
518,
384,
553,
232,
254,
241,
175,
199,
422,
266,
1125,
762,
78,
403,
327,
238,
129,
290,
267,
252,
427,
142,
418,
492,
641,
444,
477,
937,
3377,
210,
713,
391,
258,
82,
104,
160,
150,
68,
106,
37,
66,
77,
624,
440,
176,
287,
231,
279,
35,
72,
155,
210,
160,
163,
200,
67,
60,
68,
71,
261,
60,
130,
140,
72,
56,
51,
116,
59,
374,
272,
634,
610,
187,
87,
119,
545
],
"outbound": {
"DepartureDate": "2017-05-18T00:00:00",
"Carrier": "WOW air",
"DestinationId": "EWR",
"OriginId": "LGW"
},
"airline": [
"WOW air",
"Lufthansa",
"Gulf Air",
"EVA Air",
"Turkish Airlines",
"British Airways",
"Turkish Airlines",
"Pegasus Airlines",
"Pegasus Airlines",
"Singapore Airlines",
"Air India",
"British Airways",
"Pegasus Airlines",
"Vueling Airlines",
"Pegasus Airlines",
"Pegasus Airlines",
"Monarch",
"Oman Air",
"Turkish Airlines",
"British Airways",
"United",
"WOW air",
"Air Transat",
"WestJet",
"Pegasus Airlines",
"Cobalt",
"Royal Brunei ",
"Turkish Airlines",
"Pegasus Airlines",
"Pegasus Airlines",
"easyJet",
"KLM",
"Austrian Airlines",
"British Airways",
"Air India",
"Alitalia",
"British Airways",
"Avianca",
"Pegasus Airlines",
"SriLankan Airlines",
"Qatar Airways",
"Pegasus Airlines",
"Wizz Air",
"Norwegian",
"eurowings",
"eurowings",
"Vueling Airlines",
"Monarch",
"Blue Air",
"Norwegian",
"Norwegian",
"Virgin Atlantic",
"Ethiopian Airlines",
"Iberia",
"Thomson Airways",
"Wizz Air",
"Pegasus Airlines",
"Flybe",
"Wizz Air",
"Monarch",
"Air Malta",
"easyJet",
"Pegasus Airlines",
"Aegean Airlines",
"Aer Lingus",
"Vueling Airlines",
"Norwegian",
"Wizz Air",
"eurowings",
"Wizz Air",
"SWISS",
"Ukraine International",
"Vueling Airlines",
"Wizz Air",
"Flybe",
"Flybe",
"Flybe",
"British Airways",
"Pegasus Airlines",
"Qatar Airways",
"Royal Brunei ",
"Wizz Air",
"Wizz Air",
"Monarch",
"Singapore Airlines"
],
"inbound": {
"DepartureDate": "2017-05-22T00:00:00",
"Carrier": "Norwegian",
"OriginId": "JFK",
"DestinationId": "LGW"
}
},
{
"misc": {
"QuoteDateTime": "2017-04-19T06:33:00",
"MinPrice": 392,
"Direct": true,
"QuoteId": 2,
"skyLink": "http://partners.api.skyscanner.net/apiservices/referral/v1.0/AU/AUD/en-US/anywhere/amd/2017-05-18/2017-05-22?apiKey=wc161029621991497683276175998396"
},
"outbound": {
"DepartureDate": "2017-05-18T00:00:00",
"Carrier": "Lufthansa",
"DestinationId": "EWR",
"OriginId": "LHR"
},
"inbound": {
"DepartureDate": "2017-05-22T00:00:00",
"Carrier": "Austrian Airlines",
"OriginId": "EWR",
"DestinationId": "LHR"
}
}
]
You have gotten some good answers here, but all are manipulating your response and changing the build of it, instead of treating it as is. There is some other data in your response and want to retain the data, so here's a solution using Pipe instead.
You seem to have two objects in your array, but only one contains routes. Will this always be the case? If not, you might want to iterate the response and show all routes (if exists) for all objects, so I'd iterate the array first, and then iterate the routes:
<!-- Iterate array -->
<div *ngFor="let obj of jsonData">
<!-- iterate routes for each object using pipe -->
<div *ngFor="let route of obj.routes | keys">
{{route.toCity}}
</div>
</div>
And then the keys pipe:
#Pipe({ name: 'keys', pure: false })
export class KeysPipe implements PipeTransform {
transform(value: any, args?: any[]): any[] {
// check if "routes" exists
if(value) {
// create instance vars to store keys and final output
let keyArr: any[] = Object.keys(value),
dataArr = [];
// loop through the object,
// pushing values to the return array
keyArr.forEach((key: any) => {
dataArr.push(value[key]);
});
// return the resulting array
return dataArr;
}
}
}
This way you have not manipulated your response, and you have access to all other data that is coming with the response.
Demo
You will want to convert your object to an iterable array.
this.http.get('data.json')
.subscribe((res) => {
let keyArr: any[] = Object.keys(res.json()[0].routes);
keyArr.forEach((key: any) => {
this.data.push(res.json()[0].routes[key]);
});
});
Here's a Plunker
Your routes should be defined as an json array however you have done a workaround to make routes as an array where you have explicitly given indexs (0, 1 ..) which is not correct.
Solution is attached below:
JSON should look like below:
[
{
"routes": [{
"budget": 326,
"toCity": "United States",
"QuoteIds": [
1,
2
],
"options": 2
}, {
"budget": 374,
"toCity": "Thailand",
"QuoteIds": [
3,
4
],
"options": 2
}
]
}
]
Way to assign it
this.routes=resonseJson[0]['routes']
Way to iterate it in html
<div *ngFor="let route of routes">
{{route.toCity}}
</div>
You have to iterate over object keys and not array elements. Hence either use
Object.keys(responseJson[0].routes)
that will return ["0","1", ..."178"]. Then use below:
in component .ts :
routes : any = responseJson[0].routes;
in template :
<div *ngFor="let key of Object.keys(routes)">
{{routes.key.budget}}
</div>
Related
Can't parse array in another array - jq: error (at test.issues.json:100): object ({"component...) is not valid in a csv row
File test.issues.json { "issues": [ { "key": "key_1", "component": "my_component", "textRange": { "startLine": 1, "endLine": 11, "startOffset": 111, "endOffset": 1111 }, "flows": [], "status": "OPEN", "type": "BUG", "scope": "MAIN" }, { "key": "key2", "component": "my component 2", "textRange": { "startLine": 2, "endLine": 22, "startOffset": 222, "endOffset": 2222 }, "flows": [ { "locations": [ { "component": "some component", "textRange": { "startLine": 35, "endLine": 35, "startOffset": 3, "endOffset": 50 }, "msg": "any message" } ] }, { "locations": [ { "component": "another component", "textRange": { "startLine": 36, "endLine": 36, "startOffset": 3, "endOffset": 71 }, "msg": "message custom" } ] }, { "locations": [ { "component": "Alarm.java", "textRange": { "startLine": 37, "endLine": 37, "startOffset": 3, "endOffset": 76 }, "msg": "message number 2" } ] }, { "locations": [ { "component": "Alarm.java", "textRange": { "startLine": 38, "endLine": 38, "startOffset": 3, "endOffset": 50 }, "msg": "message number 3" } ] } ] }, { "key": "my_key3", "component": "my component 3", "textRange": { "startLine": 548, "endLine": 548, "startOffset": 14, "endOffset": 15 }, "flows": [], "status": "OPEN", "type": "CODE_SMELL", "scope": "LOCAL" } ] } I need to convert to csv. I try this: jq -r '.issues[] | [.key,.component,.textRange[], (.flows[].locations[]), .status, .type, .scope] | #csv' test.issues.json But I get error: "key_1","my_component",1,11,111,1111,"OPEN","BUG","MAIN" jq: error (at test.issues.json:100): object ({"component...) is not valid in a csv row I need to get smt like this: key,component,textRange,startLine,endLine,startOffset,endOffset,status,type,scope,flows,locations,component,textRange,startLine,endLine,startOffset,endOffset,msg key_1,my_component,,1,11,111,1111,OPEN,BUG,MAIN,,,,,,,,, key2,my component 2,,2,22,222,2222,,,,,,some component,,35,35,3,50,any message ,,,,,,,,,,,,another component,,36,36,3,71,message custom ,,,,,,,,,,,,Alarm.java,,37,37,3,76,message number 2 ,,,,,,,,,,,Alarm.java,,38,38,3,50,message number 3 my_key3,my component 3,,548,548,14,15,OPEN,CODE_SMELL,LOCAL,,,,,,,,,
Try this for starters jq -r ' .issues[] | (.flows |= first), (.flows[1:][] | {flows:.}) | [ .key, .component, ( .textRange | null, .startLine, .endLine, .startOffset, .endOffset ), .status, .type, .scope, ( .flows.locations[]? // {} | null, null, .component, ( .textRange | null, .startLine, .endLine, .startOffset, .endOffset ), .msg ) ] | join(",") ' key_1,my_component,,1,11,111,1111,OPEN,BUG,MAIN,,,,,,,,, key2,my component 2,,2,22,222,2222,,,,,,some component,,35,35,3,50,any message ,,,,,,,,,,,,another component,,36,36,3,71,message custom ,,,,,,,,,,,,Alarm.java,,37,37,3,76,message number 2 ,,,,,,,,,,,,Alarm.java,,38,38,3,50,message number 3 my_key3,my component 3,,548,548,14,15,OPEN,CODE_SMELL,LOCAL,,,,,,,,, Demo Note: You may want to use #csv instead of join(",") but it'll wrap the strings in quotes. Also, to add a header line, prepend the filters before the join/#csv with a simple array of strings.
How can I iterate over each item and render on the screen?
I've been trying to iterate over each item for forecast data and can't figure out where the outputs are coming from.. I'm only trying to iterate over temperature, pressure, place name, humidity, wind speed and feels like.. Json { "cod": "200", "message": 0, "cnt": 40, "list": [ { "dt": 1641124800, "main": { "temp": 11.74, "feels_like": 11.08, "temp_min": 11.74, "temp_max": 12, "pressure": 1012, "sea_level": 1012, "grnd_level": 1008, "humidity": 81, "temp_kf": -0.26 }, "weather": [ { "id": 803, "main": "Clouds", "description": "broken clouds", "icon": "04d" } ], "clouds": { "all": 75 }, "wind": { "speed": 5.3, "deg": 229, "gust": 11.75 }, "visibility": 10000, "pop": 0, "sys": { "pod": "d" }, "dt_txt": "2022-01-02 12:00:00" }, { "dt": 1641135600, "main": { "temp": 11.86, "feels_like": 11.11, "temp_min": 11.86, "temp_max": 12.09, "pressure": 1011, "sea_level": 1011, "grnd_level": 1006, "humidity": 77, "temp_kf": -0.23 }, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10d" } ], "clouds": { "all": 83 }, "wind": { "speed": 6.45, "deg": 223, "gust": 15.9 }, "visibility": 10000, "pop": 0.7, "rain": { "3h": 0.6 }, "sys": { "pod": "d" }, "dt_txt": "2022-01-02 15:00:00" }, { "dt": 1641146400, "main": { "temp": 11.29, "feels_like": 10.43, "temp_min": 11.06, "temp_max": 11.29, "pressure": 1011, "sea_level": 1011, "grnd_level": 1007, "humidity": 75, "temp_kf": 0.23 }, "weather": [ { "id": 500, "main": "Rain", "description": "light rain", "icon": "10n" } ], "clouds": { "all": 92 }, "wind": { "speed": 6.1, "deg": 250, "gust": 13.97 }, "visibility": 10000, "pop": 0.94, "rain": { "3h": 1.01 }, "sys": { "pod": "n" }, "dt_txt": "2022-01-02 18:00:00" }, { "dt": 1641157200, "main": { "temp": 9.54, "feels_like": 6.37, "temp_min": 9.54, "temp_max": 9.54, "pressure": 1012, "sea_level": 1012, "grnd_level": 1009, "humidity": 76, "temp_kf": 0 }, "weather": [ { "id": 802, "main": "Clouds", "description": "scattered clouds", "icon": "03n" } ], "clouds": { "all": 36 }, "wind": { "speed": 6.93, "deg": 244, "gust": 14.72 }, "visibility": 10000, "pop": 0, "sys": { "pod": "n" }, "dt_txt": "2022-01-02 21:00:00" }, { "dt": 1641546000, "main": { "temp": 3.96, "feels_like": 0.41, "temp_min": 3.96, "temp_max": 3.96, "pressure": 1010, "sea_level": 1010, "grnd_level": 1007, "humidity": 82, "temp_kf": 0 }, "weather": [ { "id": 804, "main": "Clouds", "description": "overcast clouds", "icon": "04d" } ], "clouds": { "all": 100 }, "wind": { "speed": 4.29, "deg": 239, "gust": 11.29 }, "visibility": 10000, "pop": 0.02, "sys": { "pod": "d" }, "dt_txt": "2022-01-07 09:00:00" } ], "city": { "id": 2643743, "name": "London", "coord": { "lat": 51.5085, "lon": -0.1257 }, "country": "GB", "population": 1000000, "timezone": 0, "sunrise": 1641110761, "sunset": 1641139355 } } in forecast.dart import 'package:forecast/models/weather_data.dart'; class ForecastData { final List list; ForecastData({required this.list}); factory ForecastData.fromJson(Map<String, dynamic> json) { var list = json['list']?.map((e) => e)?.toList(growable: true) ?? []; List weatherData = []; list.forEach((e) { WeatherData w = WeatherData( placeName: json['city']['name'], temperature: e['main']['temp'], feels_like: e['main']["feels_like"], pressure: e['main']['pressure'], humidity: e['main']['humidity'], wind_speed: e['wind']['speed']); weatherData.add(w); print(weatherData.toList()); }); return ForecastData(list: weatherData); } } weatherdata.dart class WeatherData { String? placeName; num? temperature; num? feels_like; num? pressure; num? humidity; num? wind_speed; WeatherData({ this.placeName, this.temperature, this.feels_like, this.pressure, this.humidity, this.wind_speed, }); #override String toString() => '${placeName ?? 'unknown'}${feels_like ?? 'unknown'}${temperature ?? 'unknown'}${pressure ?? 'unknown'}${humidity ?? 'unknown'}${wind_speed ?? 'unknown'}'; WeatherData.fromJson(Map<String, dynamic> json) { placeName = json['city']['name']; temperature = json['list'][0]['main']['temp']; feels_like = json['list'][0]['main']['temp']; pressure = json['list'][0]['main']['temp']; humidity = json['list'][0]['main']['temp']; wind_speed = json['list'][0]['main']['temp']; } } output I/flutter (25471): [London11.0811.741012815.3] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45, London10.4311.291011756.1] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45, London10.4311.291011756.1, London6.379.541012766.93] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45, London10.4311.291011756.1, London6.379.541012766.93, London6.229.481013757.18] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45, London10.4311.291011756.1, London6.379.541012766.93, London6.229.481013757.18, London6.039.051013796.02] I/flutter (25471): [London11.0811.741012815.3, London11.1111.861011776.45, London10.4311.291011756.1, London6.379.541012766.93, London6.229.481013757.18, London6.039.051013796.02, London5.698.681012795.66] I can't figure out where the problem is..why is my output iterating like this? I just need to iterate over each item and print out each item each time please help!
in forecast.dart, You are printing the whole weatherData list in the iterator list.forEach. Try changing , print(weatherData.toList()); to, print(w); And put some spaces in your toString ${placeName ?? 'unknown'} ${feels_like ?? 'unknown'} ${te... so that you can see where one number ends and the next starts.
I think that you shoul lose the map and review the fromJson parameters... WeatherData.fromJson(Map<String, dynamic> json) { placeName = json['city']['name']; temperature = json['list'][0]['main']['temp']; feels_like = json['list'][0]['main']['temp']; pressure = json['list'][0]['main']['temp']; humidity = json['list'][0]['main']['temp']; wind_speed = json['list'][0]['main']['temp']; }
Split an array of nested JSON objects using jq
I'm trying to split an array of nested json objects using jq. Could someone please help to resolve this issue and provide a better solution? Sample input is: { "storeId": "1412", "templateCheck": [ { "rom": 37, "updateDate": "2021-05-09 07:53:17", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-19-78-5C", "sk": "830066", "skUpdateDate": "2020-07-21 05:37:07", "battery": 30, "status": 1 }, { "rom": 37, "updateDate": "2021-05-09 07:54:02", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-1B-FE-6E", "sk": "740541", "skUpdateDate": "2021-03-22 05:59:00", "battery": 30, "status": 1 }, { "rom": 37, "updateDate": "2021-05-09 07:52:05", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-1C-22-6E", "sk": "846760", "skUpdateDate": "2021-05-08 03:34:22", "battery": 29, "status": 1 } ] } Expecting output as: { "storeId": "1412", "templateCheck": [ "rom": 37, "updateDate": "2021-05-09 07:53:17", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-19-78-5C", "sk": "830066", "skUpdateDate": "2020-07-21 05:37:07", "battery": 30, "status": 1 ] } { "storeId": "1412", "templateCheck": [ "rom": 37, "updateDate": "2021-05-09 07:54:02", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-1B-FE-6E", "sku": "740541", "skUpdateDate": "2021-03-22 05:59:00", "battery": 30, "status": 1 ] } { "storeId": "1412", "templateCheck": [ "rom": 37, "updateDate": "2021-05-09 07:52:05", "lhb": "2021-05-09 06:32:41", "templateCode": "REGULAR", "lId": "50-1C-22-6E", "sk": "846760", "skUpdateDate": "2021-05-08 03:34:22", "battery": 29, "status": 1 ] }
Sure it's possible. Assuming there are no other top-level keys that you care about, jq '.storeId as $storeId | .templateCheck[] | { $storeId, templateCheck: [ . ] }' does just fine to reproduce your example output, or maybe a little more generically (but more confusingly): jq '(. | del(.templateCheck)) as $o | .templateCheck[] | $o + { templateCheck: [.] }'
How to extract text from json with parent siblings and substrings?
https://bern.korea.ac.kr/pubmed/32818866 $ jq -r '.[] | .denotations | .[] | select(.obj=="drug") | .span | [.begin, .end] | #tsv' I am able to extract the following info from the above URL using the above jq command. 377 387 562 579 584 602 659 676 681 699 919 936 941 959 1032 1049 1054 1072 But the output that I really need is the following. The last column is just the substring of text starting from begin+1 to end (suppose the string in text is indexed starting from 1. I don't know how to extract this info using just jq as it involves taking a parent sibling element and the substring of another parent sibling element. Could anybody show me how to extract the output in this format? Thanks. 32818866 377 387 silica gel 32818866 562 579 7-methoxycoumarin 32818866 584 602 8-prenylkaempferol 32818866 659 676 7-methoxycoumarin 32818866 681 699 8-prenylkaempferol 32818866 919 936 7-methoxycoumarin 32818866 941 959 8-prenylkaempferol 32818866 1032 1049 7-methoxycoumarin 32818866 1054 1072 8-prenylkaempferol The json txt is here for the completeness of this message. [ { "project": "BERN", "sourcedb": "PubMed", "sourceid": "32818866", "text": "Identification of two bitter components in Zanthoxylum bungeanum Maxim. and exploration of their bitter taste mechanism through receptor hTAS2R14. Bitterness is an inherent organoleptic characteristic affecting the flavor of Zanthoxylum bungeanum Maxim. In this study, the vital bitter components of Z. bungeanum were concentrated through solvent extraction, sensory analysis, silica gel chromatography, and thin-layer chromatographic techniques and subsequently identified by UPLC-Q-TOF-MS. Two components with the highest bitterness intensities (BIs), such as 7-methoxycoumarin and 8-prenylkaempferol were selected. The bitter taste perceived thresholds of 7-methoxycoumarin and 8-prenylkaempferol were 0.062 mmol/L and 0.022 mmol/L, respectively. Moreover, the correlation between the contents of the two bitter components and the BIs of Z. bungeanum were proved. The results of siRNA and flow cytometry showed that 7-methoxycoumarin and 8-prenylkaempferol could activate the bitter receptor hTAS2R14. The results concluded that 7-methoxycoumarin and 8-prenylkaempferol contribute to the bitter taste of Z. bungeanum.", "denotations": [ { "id": [ "NCBI:txid328401" ], "span": { "begin": 43, "end": 64 }, "obj": "species" }, { "id": [ "CUI-less" ], "span": { "begin": 128, "end": 145 }, "obj": "gene" }, { "id": [ "NCBI:txid328401" ], "span": { "begin": 225, "end": 246 }, "obj": "species" }, { "id": [ "NCBI:txid328401" ], "span": { "begin": 300, "end": 312 }, "obj": "species" }, { "id": [ "MESH:D058428", "BERN:315272203" ], "span": { "begin": 377, "end": 387 }, "obj": "drug" }, { "id": [ "CHEBI:5679", "BERN:4597103" ], "span": { "begin": 562, "end": 579 }, "obj": "drug" }, { "id": [ "MESH:C532177", "BERN:280529003" ], "span": { "begin": 584, "end": 602 }, "obj": "drug" }, { "id": [ "CHEBI:5679", "BERN:4597103" ], "span": { "begin": 659, "end": 676 }, "obj": "drug" }, { "id": [ "MESH:C532177", "BERN:280529003" ], "span": { "begin": 681, "end": 699 }, "obj": "drug" }, { "id": [ "NCBI:txid328401" ], "span": { "begin": 841, "end": 853 }, "obj": "species" }, { "id": [ "CHEBI:5679", "BERN:4597103" ], "span": { "begin": 919, "end": 936 }, "obj": "drug" }, { "id": [ "MESH:C532177", "BERN:280529003" ], "span": { "begin": 941, "end": 959 }, "obj": "drug" }, { "id": [ "CUI-less" ], "span": { "begin": 979, "end": 994 }, "obj": "gene" }, { "id": [ "CUI-less" ], "span": { "begin": 995, "end": 1003 }, "obj": "gene" }, { "id": [ "CHEBI:5679", "BERN:4597103" ], "span": { "begin": 1032, "end": 1049 }, "obj": "drug" }, { "id": [ "MESH:C532177", "BERN:280529003" ], "span": { "begin": 1054, "end": 1072 }, "obj": "drug" }, { "id": [ "NCBI:txid328401" ], "span": { "begin": 1107, "end": 1119 }, "obj": "species" } ], "timestamp": "Wed Oct 28 21:43:04 +0000 2020", "logits": { "disease": [], "gene": [ [ { "start": 128, "end": 145, "id": "CUI-less" }, 0.7066106796264648 ], [ { "start": 979, "end": 994, "id": "CUI-less" }, 0.9999749660491943 ], [ { "start": 995, "end": 1003, "id": "CUI-less" }, 0.9052715301513672 ] ], "drug": [ [ { "start": 377, "end": 387, "id": "MESH:D058428\tBERN:315272203" }, 0.999982476234436 ], [ { "start": 562, "end": 579, "id": "CHEBI:5679\tBERN:4597103" }, 0.9999980926513672 ], [ { "start": 584, "end": 602, "id": "MESH:C532177\tBERN:280529003" }, 0.9999980926513672 ], [ { "start": 659, "end": 676, "id": "CHEBI:5679\tBERN:4597103" }, 0.9999980926513672 ], [ { "start": 681, "end": 699, "id": "MESH:C532177\tBERN:280529003" }, 0.9999980330467224 ], [ { "start": 919, "end": 936, "id": "CHEBI:5679\tBERN:4597103" }, 0.9999980926513672 ], [ { "start": 941, "end": 959, "id": "MESH:C532177\tBERN:280529003" }, 0.9999980926513672 ], [ { "start": 1032, "end": 1049, "id": "CHEBI:5679\tBERN:4597103" }, 0.9999980926513672 ], [ { "start": 1054, "end": 1072, "id": "MESH:C532177\tBERN:280529003" }, 0.9999980926513672 ] ], "species": [ [ { "start": 43, "end": 64, "id": "NCBI:txid328401" }, 0.9999997615814209 ], [ { "start": 225, "end": 246, "id": "NCBI:txid328401" }, 0.9999998211860657 ], [ { "start": 300, "end": 312, "id": "NCBI:txid328401" }, 0.9999998211860657 ], [ { "start": 841, "end": 853, "id": "NCBI:txid328401" }, 0.9999998211860657 ], [ { "start": 1107, "end": 1119, "id": "NCBI:txid328401" }, 0.9999998211860657 ] ] }, "elapsed_time": { "tmtool": 0.991, "ner": 0.453, "normalization": 0.172, "total": 1.617 } } ]
Assuming the first column of the desired output is the "sourceid", we can adapt your solution as follows: .[] | .sourceid as $id | .text as $text | .denotations[] | select(.obj=="drug") | .span | [$id, .begin, .end, $text[.begin : .end] ] | #tsv
Hapi.js response with "type":"Buffer"
I have hapi.js, sequelize with mysql with script like this : method: 'GET', path: `/${GROUP_NAME}`, options: { tags: ['api', GROUP_NAME], description: 'Mendapatkan jumlah tempat tidur berdasarkan kelas', notes: 'Mendapatkan jumlah tempat tidur', handler: async (request, h) => { return jlhttidurbyjenis.findAll({ attributes: ['VIP','KELAS 1','KELAS 2','KELAS 3','ICU','NICU','PICU','HCU','ICCU','ISOLASI']}) }, validate: { }, response: { } } when I test with postman it response like this : [ { "VIP": { "type": "Buffer", "data": [ 50, 47, 50, 50 ] }, "KELAS 1": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "KELAS 2": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "KELAS 3": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "ICU": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "NICU": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "PICU": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "HCU": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "ICCU": { "type": "Buffer", "data": [ 48, 47, 48 ] }, "ISOLASI": { "type": "Buffer", "data": [ 48, 47, 48 ] } } ] How to fix the script so the response will be the same with database content, it will be like this : [ { "VIP": "12/22", "KELAS 1": "0/0", "KELAS 2": "0/0", "KELAS 3": "0/0", "ICU": "0/0", "NICU": "0/0", "PICU": "0/0", "HCU": "0/0", "ICCU": "0/0", "ISOLASI": "0/0" } ]
That looks like a serialization issue from sequilize. Look at available configurations for JSON serialization with regards to buffer.