tags:

views:

102

answers:

2

Hi All

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!

A: 
$("#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

douwe
Great!! Thanks man! It worked!!!!!!!
Bala
var json = "[{'City':'Lucknow','ID':'1'},{'City':'Mumbai','ID':'2'}]"; $.each(eval(json), function() { alert(this['City']); });-- Only this works.The above code with pasrJSON does not work. I am using jquery 1.4.1
Bala
+3  A: 

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"}]';
Gumbo
Thanks for teh reply! Even this doesnt work...
Bala
@Bala: Oh, `jQuery.parseJSON` was added in 1.4.1. Maybe your jQuery version does not support it.
Gumbo
i use jquery 1.4.1
Bala
@Bala: Then it is supposed to be available. Try is also with the shortcut of `jQuery`: `$.parseJSON`.
Gumbo
@Bala: Now I know where the problem is: JSON only allows double quotes for strings. So `jQuery.parseJSON('[{"City":"Lucknow","ID":"1"},{"City":"Mumbai","ID":"2"}]')` should work.
Gumbo
Thats right!!! Thanks Gumbo!!!!
Bala