Reputation: 2128
I have a JSON string that looks like this:
{"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
In Javascript, I'm trying to output the strings by category (cat1-3), this is my code so far.
$.post(loadUrl, function(data){
$("#result").html("<p>Cat1: " + data.cat1 + "</p><p>Cat2: " + data.cat2 + "</p>");
});
I would normally not use JSON (Usually JSTL) but since I want to learn AJAX, I want to try output the cat1-3 values by the key, which I keep getting "undefined".
I was using this as a guide to get the values: http://www.skill-guru.com/blog/2010/01/27/json-javascript-tutorial/
Upvotes: 0
Views: 223
Reputation: 1940
Try below script
va response = {"cat1":"m1","cat2":["d1","d2","d3"],"cat3":["m1","m2","m3","m4"]}
var obj = jQuery.parseJSON(response);
alert(obj.cat1);
it will return m1
Upvotes: 3
Reputation: 2672
var a = JSON.parse("{\"cat1\":\"m1\",\"cat2\":[\"d1\",\"d2\",\"d3\"],\"cat3\":[\"m1\",\"m2\",\"m3\",\"m4\"]}");
for(key in a)
{
alert(key);
alert(a[key]);
}
Upvotes: 1