Reputation: 185
I have an ajax call that returns JSON data (Data Attached).
After converting the data into String, this is how it looks like:
{
"shipments":[
{
"companyName":"TriStar Inc.",
"shipmentDate":null,
"transMode":"NDAY",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"DAISY N.",
"customerZip":"90544"
},
"orderStatus":true
},
{
"companyName":"Carbo Box",
"shipmentDate":null,
"transMode":"COUR",
"paid":true,
"delDate":null,
"custRefInfo":{
"customerName":"TOM K",
"customerZip":"07410"
},
"orderStatus":true
}
]
}
Now when I print the JSON response in Firefox, it looks like:
[Object { companyName="TriStar Inc.", shipmentDate=null, transMode="NDAY", more...}, Object { companyName="Carbo Box", shipmentDate=null, transMode="COUR", more... } ]
My question is, how do I extract companyName and customerName field out of this response. The following isnt working:
load: function(response){
for(var i in response){
console.log(response.shipments[i].companyName);
}
Upvotes: 0
Views: 484
Reputation: 120188
if you get a string that is json, you need to parse it first.
var obj = JSON.parse(jsonString);
now you have a proper object literal, and you can access it normally
var shipments = obj.shipments;
shipments
is now a javascript array...
for(var i = 0; i < shipments.length; i++){
console.log(shipments[i].companyName);
}
note you should not use the for(var i in x)
construct on arrays.
Upvotes: 2