Reputation: 584
I Have this kind of JSON Object
"{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
I want to get exactly the string "macchina" and "pollo", which are the keys text/value (I get the Object from an ajax, so "9 Marzo" would be like response.date
), and same for "si" and "no", I cannot arrive to them.
I have tryed console.log(response.alimenti[i][0]);
but it's undefined.
i come from the cicle: for (i = 0; i < response.ruoli.length; i++)
Upvotes: 0
Views: 1630
Reputation: 51
This will get you to the strings "macchina" and "pollo":
var json = "{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": [{ \"macchina\":\"si\", \"pollo\":\"no\" }] }";
var obj = JSON.parse(json);
for (var k in obj.alimenti[0]) {
console.log(k);
}
or their values:
for (var k in obj.alimenti[0]) {
console.log(obj.alimenti[0][k]);
}
Upvotes: 1
Reputation: 1035
Using response.alimenti[i][0]
won't work because alimenti is an array of object(s), not an array of arrays.
This instead:
var alimenti = response.alimenti[0];
console.log(alimenti.maccina);
console.log(alimenti.pollo);
Example: http://jsfiddle.net/zcuwfb9s/
Upvotes: 1
Reputation: 451
You'd be better off parsing the JSON object and then extracting the string from the javascript object.
i.e var obj = JSON.parse("{\"date\": \" 9 Marzo\", \"time\": \" 07:00 - 13:20\", \"descrizione\": \" concerto\", \"alimenti\": { \"macchina\":\"si\", \"pollo\":\"no\" } }";);
console.log(obj.alimenti[0].macchina);
or pollo
console.log(obj.alimenti[0].pollo);
Also, that object structure is a little weird. You might want to remove the array from within the alimenti to better access the data.
Upvotes: 1