jquery解析json报错_使用jQuery.parseJSON的JSON解析错误

bd96500e110b49cbb3cd949968f18be7.png

This code fails with an exception indicating invalid JSON:

var example = '{ "AKEY": undefined }';

jQuery.parseJSON(example);

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

解决方案

If you can wrap your head around this, the token undefined is actually 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');

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!

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

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

typeof(example.AKEY) == 'undefined'

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值