在Jquery中读取JSON字符串 [英] Reading JSON string in Jquery

查看:102
本文介绍了在Jquery中读取JSON字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我尝试读取如下所示的JSON字符串时,它会陷入无限循环.

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!

推荐答案

使用 jQuery.parseJSON 使用jQuery解析JSON字符串:

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']);
});

jQuery.parseJSON的优点在于,如果支持,它将使用浏览器的本机实现JSON.parse.

The advantage of jQuery.parseJSON is that it uses the native implementation JSON.parse of the browser if it supports it.

编辑.不起作用的问题可能是JSON只允许使用双引号声明字符串.相应的摘自JSON规范:

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"}]';

这篇关于在Jquery中读取JSON字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆