关于json的反序列化问题

jquery反序列化组件对json的数据格式标准要求比较严格,比如:属性也要添加引号,并且只能是双引号

对于缺少双引号的非标准json格式,可以使用eval进行发序列化。比如对于下面这个非标准json字符串(属性没有双引号):

{name:'fiona',age:7}"

第一种,json原生反序列化方式,可以正常反序列化

var jsonstr="{name:'fiona',age:7}"
var x=eval("("+jsonstr+")");
console.log(x.name);

结果:打印fiona

第二种,jquery反序列化方式,不能正常反序列化

 

先注册jquery组件

var script = document.createElement('script');
script.src = 'http://libs.baidu.com/jquery/1.9.0/jquery.js';
document.body.appendChild(script);

例子1:不支持单引号

var jsonstr="{name:'fiona',age:7}"
var test=$.parseJSON(jsonstr);
console.log(test.name);
结果:报异常,Unexpected token '

 

例子2:属性没有双引号

var jsonstr="{name:\"fiona\",age:7}"
var test=$.parseJSON(jsonstr);
console.log(test.name);

结果:报异常,Unexpected token a

例子3:属性和字符串值都有双引号

var jsonstr="{\"name\":\"fiona\",\"age\":7}"
var test=$.parseJSON(jsonstr);
console.log(test.name);

结果:正常输出

 

posted @ 2016-04-22 13:58  灰衣僧  阅读(468)  评论(0编辑  收藏  举报