I have the following Json string
{ "Users" : [
{ 开发者_如何学Python"Name" : "user99",
"Value" : "test"
},
{ "Name" : "test2",
"Value" : "test"
}
]
}
I am trying to parse it and print out each name and value - what is the easiest way to do this ? I tried jQuery.parseJSON but I do not know how to use it I guess
Sample code would be great
var json = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
var json_parsed = $.parseJSON(json);
for (var u = 0; u < json_parsed.Users.length; u++){
var user = json_parsed.Users[u];
$('body').append($('<p>').html('User: '+user.Name+'<br />Value: '+user.Value));
}
Results in:
<p>User: user999<br />Value: test</p>
<p>User: test2<br />Value: test</p>
jsFiddle Example: http://jsfiddle.net/bradchristie/XtzjZ/1/
You actually have an array of objects so..
var obj = $.parseJSON(string);
var users = obj.users;
for x in users {
alert(users[x].Name);
alert(users[x].Value);
}
You can use jQuery.parseJSON, here's an example:
var jsonString = '{"key":"value","otherkey":"othervalue"}';
data = $.parseJSON(jsonString);
alert(data.key); // Shows: value
<script>
var str = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
str = eval('('+str+')');
alert(str.Users[0].Name);
//var str = '{"x":{"a":"1"}}';
//alert(str.x.a);
</script>
For the JSON you have given, $.parseJSON
should return an object, myObj
, that can be accessed like so:
var users = myObj.Users,
user0_name = users[0].Name;
精彩评论