'How to parse a nested json in angular
I have a complex nested json and I want to parse and display the data in html.
My json looks like:
{
"Test Data": [
{
"First Test": {
"Design Name": "testname",
"Output": "1",
"Data Info": [
{
"Test Name": "ft",
"Time": 10,
}
]
}
},
{
"First Test": {
"Design Name": "testname2",
"Output": "1",
"Data Info": [
{
"Test Name": "ft2",
"Time": 10,
}
]
}
},
]
}
This is a subset of my json. How to parse this data and get the array of Design Names
Solution 1:[1]
This is valid JSON so you can use JSON.parse() method. And then you can use map method to iterate over and get design names like following:
let myData = JSON.parse(response); // response is the JSON that you provided
let designNames = myData['Test Data'].map(data => data['"First Test"']['Design Name']);
Hope this helps
Solution 2:[2]
If your JSON keys does not have spaces:
{
"rootElement": {
"firstElem": "Some data",
"secondElem": {
"thirdLevelElem": "Yet some other data"
}
}
}
You can do this:
const myJsonData = JSON.parse(response);
let firstElement = myJsonData?.rootElement?.firstElem;
let nestdElement = myJsonData?.rootElement?.secondElem?.thirdLevelElem;
Solution 3:[3]
DEMO
let myData = {
"Test Data": [
{
"First Test": {
"Design Name": "testname",
"Output": "1",
"Data Info": [
{
"Test Name": "ft",
"Time": 10
}
]
}
},
{
"First Test": {
"Design Name": "testname2",
"Output": "1",
"Data Info": [
{
"Test Name": "ft2",
"Time": 10
}
]
}
}
]
};
var result = myData['Test Data'].map(data => data["First Test"]['Design Name']);
console.log(result);
Solution 4:[4]
I have the same complex nested json too and I want to parse and display the data in html.
My json looks like:
{
"text": "Apple",
"userName": "Alex",
"dtoList": [
{
"text": "Banana",
"userName": "Sam",
"dtoList": [
{
"text": "Mango",
"userName": "Alex",
"dtoList": [],
},
],
},
{
"text": "Kiwi",
"userName": "Clover",
"dtoList": [
{
"text": "Carrots",
"userName": "Alex",
"dtoList": [],
},
],
},
{
"text": "Beef",
"userName": "Adam",
"dtoList": [],
},
],
},
{
"text": "Egg",
"userName": "Adam",
dtoList: [
{
"text": "Broccoli",
"userName": "Alex",
"dtoList": [],
},
{
"text": "Pumpkin",
"userName": "Sam",
"dtoList": [
{
"text": "Brussels sprouts",
"userName": "Adam",
"dtoList": [],
},
{
"text": "Fruit loops",
"userName": "Clover",
"dtoList": [],
},
],
},
],
},
How to parse this data in angular T_T
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harun Yilmaz |
| Solution 2 | MÄris Rubenis |
| Solution 3 | Sajeetharan |
| Solution 4 |
