befidled
asked on
Need help extracting JSON data
I've got the following JSON structure and I need to access the content inside the square brackets []. Is there a way to access using the "spirits" node, or do I need to use preg_match to get the content between the brackets?
I'd like to return the content in a JSON format and with no whitespace like this:
jsonstamp({
"product":{
"item":{
"videofeed":29,
"page":120,
"weight":"12oz",
"audiofeed":"14dbl",
"taxable":1
},"item":{
"videofeed":591,
"page":124,
"weight":"18oz",
"audiofeed":"14dbl"
"taxable":1
},"item":{
"videofeed":705,
"page":144,
"weight":"20oz",
"audiofeed":"14dbl"
"taxable":1
},"item":{
"spirits":
[{
"id":1864,
"price":"$12.50",
"type":"whisky,
"taxable":0
},{
"id":1865,
"price":"$12.50",
"type":"porter",
"taxable":0
},{
"id":1866,
"price":"$13.50",
"type":"whisky3,
"taxable":1
}],
"videofeed":1866,
"page":184,
"weight":"12oz",
"audiofeed":"19dbl",
"taxable":0
},"item":{
"videofeed":1592,
"page":1192,
"weight":"14oz",
"audiofeed":"14dbl",
"taxable":1
}
})
I'd like to return the content in a JSON format and with no whitespace like this:
[{"id":1864,"price":"$12.50","type":"whisky,"taxable":0},{"id":1865,"price":"$12.50","type":"porter","taxable":0},{"id":1866,"price":"$13.50","type":"whisky3,"taxable":1}]
Where have you "got" this structure? Is it in your server-side PHP script or in your browser-side JavaScript?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Looking at your JSON string it's strange to me that you have so many "item" elements, I think you should use some sort of collection to store each "item" class element, something like:
Open in new window
This way, once you load your whole class into an object, you could retrieve your spirits just looping through item array in search of spirits value.
var x = 0;
var found = false;
var spirits;
while (x < yourObject.items.length and !found) {
if (yourObject.items[x].spiri
spirits = yourObject.items[x].spirit
found = true;
}
x++;
}
Then you'll have an spirits array loaded with your data, and you can return it as a JSON string simply looping through it and building a string.