使用jQuery.parseJSON的JSON解析错误 [英] JSON Parse Error Using jQuery.parseJSON

查看:1064
本文介绍了使用jQuery.parseJSON的JSON解析错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码失败,异常表示无效的JSON:

This code fails with an exception indicating invalid JSON:

var example = '{ "AKEY": undefined }';
jQuery.parseJSON(example);

我能够通过用空字符串替换所有未定义来修复它。未定义的是不是JSON的一部分吗?

I was able to fix it by replacing all undefineds with empty strings. Are undefineds not part of JSON?

推荐答案

如果你可以解决这个问题,令牌 undefined 实际上是未定义的。

If you can wrap your head around this, the token undefined is actually undefined.

请允许我详细说明:即使JavaScript有一个名为undefined的特殊原始值, undefined 是JavaScript关键字,也没有任何特殊含义。你可以通过比较 undefined 来破坏测试对象存在的代码。

Allow me to elaborate: even though JavaScript has a special primitive value called undefined, undefined is not a JavaScript keyword nor does it have any special meaning. You can break code which tests for the existance of an object by comparing to undefined by defining it.

var obj = { BKEY: 'I exist!' };
if (obj.AKEY == undefined) console.log ('no AKEY');
if (obj.BKEY == undefined) console.log ('should not happen');

undefined='uh oh';

if (obj.AKEY == undefined) console.log ('oops!'); // Logically, we want this to execute, but it will not!
if (obj.BKEY == undefined) console.log ('should not happen');

唯一的控制台输出是'no AKEY'。在我们分配到全局变量 undefined 之后, obj.AKEY == undefined 变为false,因为 undefined !='呃哦' obj.BKEY == undefined 仍然返回false,但这只是因为我们很幸运。如果我设置了 obj.BKEY ='呃哦',那么 obj.BKEY == undefined true 即使它确实存在

The only console output will be 'no AKEY'. After we've assigned to the global variable undefined, obj.AKEY == undefined becomes false because undefined != 'uh oh'. obj.BKEY == undefined still returns false, but only because we're lucky. If I had set obj.BKEY='uh oh', then obj.BKEY == undefined would be true, even though it actually exists!

您可能希望明确设置 AKEY null 。 (顺便说一下, null 一个关键字; null ='呃哦'抛出例外)。

You probably want to explicity set AKEY to null. (By the way, null is a keyword; null='uh oh' throws an exception).

你也可以从你的JSON中省略 AKEY ,在这种情况下你会发现: / p>

You could also simply omit AKEY from your JSON, in which case you would find:

typeof(example.AKEY) == 'undefined'

(如果将 AKEY 设置为 null ,则 typeof(example.AKEY)=='object'。)

(If you set AKEY to null, then typeof(example.AKEY) == 'object'.)

设置为null和省略之间的唯一真正区别是是否希望密钥出现在foreach循环中。

The only real difference between setting to null and omitting is whether you want the key to appear in a foreach loop.

这篇关于使用jQuery.parseJSON的JSON解析错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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