Reputation: 3213
So I have the following JSON that is being displayed on an order confirmation page:
var orderDetails = {
"orderID": "o32770183",
"orderQty": 3,
"orderTotal": 575.97,
"orderShipping": 49.97,
"orderDiscount": 0,
"orderTax": 39.74,
"orderCity": "Norwalk",
"orderState": "Connecticut",
"itemId": [
"sku500134",
"sku230312",
"sku133846"
],
"itemQty": [
1,
1,
1
],
"itemPrice": [
159.99,
225.99,
189.99
],
"itemName": [
"The 'Inaugural' Raymond R Cabernet Sauvignon",
"H de l'Hospitalet",
"Chateau Florie Aude"
]
}
What would be the best approach to pulling the data out?
Upvotes: 1
Views: 384
Reputation: 335
Here is a helpful JSON Editor tool that gives you a visual representation of your JSON object. It lists your named items and gives you the path to access your JSON values: JSON Editor
Upvotes: 0
Reputation: 83366
That's actually not JSON, that's a plain old JavaScript object. You pull the data our just like with any other object
var orderId = orderDetails.orderID;
or
var orderId = orderDetails["orderID"];
or for arrays:
var itemQtyArr = orderDetails.itemQty;
for(var i = 0, max = itemQtyArr.length; i < max; i++){
console.log("itemQty", i, itemQtyArr[i]);
}
or the dynamic approach Vivek posted (+1 to him)
Upvotes: 2
Reputation: 7227
You can iterate the keys of a Javascript Object using for in
Lets say
a = {"a":"hello","b":"world"};
for(var c in a){
console.log(c); //will out put a,b in iterations
console.log(a[c]) //will access values of keys a and b from the object a output hello, world
}
Upvotes: 1
Reputation: 4358
Or also, like this - a more dynamic approach - (if you dont know the objects elements)
for(i in orderDetails)
alert(orderDetails[i])
Upvotes: 3