$ .parseJSON()在有效对象上返回null [英] $.parseJSON() returns null on valid object

查看:367
本文介绍了$ .parseJSON()在有效对象上返回null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

jsfiddle链接

var x = {
    "Item1" : 1,
    "Item2" : {
        "Item3" : 3
    }
}

   alert(JSON.stringify(x, undefined, 2));
   alert($.parseJSON(x));

第一个警报有效对象.第二个警报为空.在实际代码中,"x"变量可以是字符串或对象,因此我应该能够解析这两种类型.我想念什么吗?

First one alerts valid object. The second one alerts null. In the real code, the "x" variable can be string or an object, so I should be able to parse both types. Am I missing something?

推荐答案

您正在解析一个对象.您解析字符串,而不是对象; jQuery.parseJSON 仅接受字符串.从文档中:

You're parsing an object. You parse strings, not objects; jQuery.parseJSON only takes strings. From the documentation:

jQuery.parseJSON(json)
json
要解析的JSON字符串.
jQuery.parseJSON( json )
json
The JSON string to parse.

用法:

if (! window.console) {
    console = {
        log: function (msg) {
            alert(msg);
        }
    };
}

console.log($.parseJSON(JSON.stringify(x, undefined, 2)));

标准jQuery似乎没有JSON字符串化器.通常,jQuery会为您处理该操作,因此没有必要.如果需要,可以使用各种插件.

Standard jQuery doesn't appear to have a JSON stringifier. Typically, jQuery handles that for you, so it isn't necessary. If you need it, there are various plugins.

这篇关于$ .parseJSON()在有效对象上返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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