'extracting data from json string
I am new to using javascript as well as json. I need to extract certain sections from json for processing the data.
{
"status": "SUCCESS",
"status_message": "blah blah blah",
"pri_tag": [
{
"tag_id": 1,
"name": "Tag1"
},
{
"tag_id": 2,
"name": "Tag2"
},
{
"tag_id": 3,
"name": "Tag3"
},
{
"tag_id": 4,
"name": "Tag4"
}
]
}
From the above json message I need to extract pri_tag section so that the extracted json should look like below:
[
{name:'Tag1', tag_id:1},
{name:'Tag2', tag_id:2},
{name:'Tag3', tag_id:3},
{name:'Tag4', tag_id:4},
{name:'Tag5', tag_id:5},
{name:'Tag6', tag_id:6}
];
How to get this done using javascript? Please help me. Thanks in advance.
Thanks friends. I was able to get this working. Thanks once again.
Solution 1:[1]
try this:
var data={
"status": "SUCCESS",
"status_message": "blah blah blah",
"pri_tag": [
{
"tag_id": 1,
"name": "Tag1"
},
{
"tag_id": 2,
"name": "Tag2"
},
{
"tag_id": 3,
"name": "Tag3"
},
{
"tag_id": 4,
"name": "Tag4"
}
]
};
if you get the data from Ajax request you need to parse it like this:
var newData=JSON.parse(data).pri_tag;
if not, you don't need to parse that:
var newData=data.pri_tag;
Solution 2:[2]
var data={
"status": "SUCCESS",
"status_message": "blah blah blah",
"pri_tag": [
{
"tag_id": 1,
"name": "Tag1"
},
{
"tag_id": 2,
"name": "Tag2"
},
{
"tag_id": 3,
"name": "Tag3"
},
{
"tag_id": 4,
"name": "Tag4"
}
]
}
use this code
var result=data.pri_tag;
for(var i in result)
{
console.log(result[i]);
}
Solution 3:[3]
Try this
var foo = '{"status": "SUCCESS","pri_tag": [...]}'
var bar = JSON.parse(foo)
bar.pri_tag
Solution 4:[4]
Hopefully this helps someone, I have a scenario where retrieving JSON.parse(someJsonObject).someAttribute doesn't work. Alternatively, you can also extract attribute data using JSON.parse(someJsonObject)['someAttribute']:
Solution 5:[5]
Assuming you have a data variable containing the JSON object, result would hold what you expect (without using the same data variable):
var result = [];
for(var i = 0; i < data.pri_tag.length; i++){
result.push({'name': data.pri_tag[i].name, 'tag_id': data.pri_tag[i].tag_id});
}
console.log(result);
Here you are a working example.
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 | |
| Solution 2 | Murugan Pandian |
| Solution 3 | xiaoboa |
| Solution 4 | jawn |
| Solution 5 | jarandaf |
