Reputation: 27087
What is the best way to extract data from inline JSON into JS DOM.
<script id="catjson" type="application/json">
{
"Page": [
{
"catfull": [
{
"id": "1",
"tag": "seotag1",
"link": "http://somelink1/",
"toptext": "top text 1",
"bottomtext": "bottom text 1",
"src": "http://*****/media/wysiwyg/assets/pages/timberland/middlespot1.jpg",
"type": "image"
},
{
"id": "2",
"tag": "seotag2",
"link": "http://somelink2/",
"toptext": "top text 2",
"bottomtext": "bottom text 2",
"src": "http://****/media/wysiwyg/assets/pages/timberland/middlespot2.jpg",
"type": "image"
}
]
}
]
}
</script>
I would like to extract certain elements from this JSON (such as the image src for Id 2)
I have tried:
var str = JSON.parse(document.getElementById('catjson').innerHTML);
console.log(str.Page.catfull.id[1].src);
This does not work and says that the path does not exist. This works console.log(str.Page);
but that spits the full JSON.
Upvotes: 0
Views: 343
Reputation: 7134
var data = JSON.parse($("#catjson").html());
console.log(data.Page[0].catfull[0].src);
https://jsfiddle.net/79Lw769c/3/ here is a fiddle for you, I used jquery, btw
or in your original code just put the right indexes
console.log(str.Page[0].catfull[0].src);
Upvotes: 2
Reputation: 101
var str = JSON.parse(document.getElementById('catjson').innerHTML);
console.log(str.Page.catfull[1].src);
catfull[0] is the first one (id 1), and so on.
Upvotes: 0