When i try to read a JSON string like below it goes to endless loop.
&开发者_如何学运维lt;script language="javascript">
$(document).ready(function() {
$("#Button1").click(function() {
var json = "[{'City':'Lucknow','ID':'1'},{'City':'Mumbai','ID':'2'}]";
$.each(json, function() {
alert(this['City']);
});
});
</script>
Not sure what i am doing wrong? Please helpme out!
Use jQuery.parseJSON
to parse the JSON string with jQuery:
var json = "[{'City':'Lucknow','ID':'1'},{'City':'Mumbai','ID':'2'}]";
$.each(jQuery.parseJSON(json), function() {
alert(this['City']);
});
The advantage of jQuery.parseJSON
is that it uses the native implementation JSON.parse
of the browser if it supports it.
Edit The problem that this is not working is probably that JSON does only allow strings to be declared with double quotes. The corresponding excerpt from the JSON specification:
string = quotation-mark *char quotation-mark char = unescaped / escape ( %x22 / ; " quotation mark U+0022 %x5C / ; \ reverse solidus U+005C %x2F / ; / solidus U+002F %x62 / ; b backspace U+0008 %x66 / ; f form feed U+000C %x6E / ; n line feed U+000A %x72 / ; r carriage return U+000D %x74 / ; t tab U+0009 %x75 4HEXDIG ) ; uXXXX U+XXXX escape = %x5C ; \ quotation-mark = %x22 ; " unescaped = %x20-21 / %x23-5B / %x5D-10FFFF
So the following should work:
var json = '[{"City":"Lucknow","ID":"1"},{"City":"Mumbai","ID":"2"}]';
$("#Button1").click(function() {
var json = $.parseJSON("[{'City':'Lucknow','ID':'1'},{'City':'Mumbai','ID':'2'}]");
$.each(json, function() {
alert(this['City']);
});
It's better to use json2.js from: http://www.json.org/js.html
精彩评论