When i try to read a JSON string like below it goes to endless loop.
<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"}]';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With