您的位置:首页 > Web前端 > JavaScript

js实现字符串转JSON格式

2019-07-31 23:48 1811 查看

  在浏览器前端实现字符串转JSON格式,有多种方法,总结如下:

  • 方法1.  js函数,eval()

语法:

var obj = eval ("(" + txt + ")");  //必须把文本包围在括号中,这样才能避免语法错误

eval()定义:eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码。

由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 eval() 可用于将 JSON 文本转换为 JavaScript 对象。

注意:当字符串中包含表达式时,eval() 函数也会编译并执行,转换会存在安全问题。

参考:JSON 使用 | 菜鸟教程JavaScript eval() 函数

 

  • 方法2.  浏览器自带对象JSON,JSON.parse()

语法:

JSON.parse(text[, reviver])
//text:必需, 一个有效的 JSON 字符串。解析前要确保你的数据是标准的 JSON 格式,否则会解析出错。
//reviver: 可选,一个转换结果的函数, 将为对象的每个成员调用此函数。

JSON.parse()比eval()安全,而且速度更快。支持主流浏览器:Firefox 3.5,IE 8,Chrome,Opera 10,Safari 4。

注意:IE8兼容模式,IE 7,IE 6,会存在兼容性问题。

解决方法:引入json2.jsJSON官网

<!--[if lte IE 7]>
<script src="json2.js"></script>
<![endif]-->

json2.js关键源码分析:

//paring过程分为4个步骤。
//第一个步骤是将unicode字符替换为转义字符。
//js在处理多种字符时是有问题的,不是悄悄的删掉他们,就是把他们当作行结束符。
text = String(text);
cx.lastIndex = 0;
if (cx.test(text)) {
text = text.replace(cx, function (a) {
return '\\u' +
('0000' + a.charCodeAt(0).toString(16)).slice(-4);
});
}

//第二个步骤如下:
// In the second stage, we run the text against regular expressions that look
// for non-JSON patterns. We are especially concerned with '()' and 'new'
// because they can cause invocation, and '=' because it can cause mutation.
// But just to be safe, we want to reject all unexpected forms.

// We split the second stage into 4 regexp operations in order to work around
// crippling inefficiencies in IE's and Safari's regexp engines. First we
// replace the JSON backslash pairs with '@' (a non-JSON character). Second, we
// replace all simple value tokens with ']' characters. Third, we delete all
// open brackets that follow a colon or comma or that begin the text. Finally,
// we look to see that the remaining characters are only whitespace or ']' or
// ',' or ':' or '{' or '}'. If that is so, then the text is safe for eval.

if (/^[\],:{}\s]*$/
.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@')
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']')
.replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {

//第三步骤:调用eval命令
//'{'在js中有语法歧义倾向:可以是程序块或者对象字面值。所以这里使用括号来避免歧义
j = eval('(' + text + ')');
json2.js关键源码

参考:JSON.parse() | 菜鸟教程json2.js 简析(个人学习) - 奋斗小小鸟的专栏

 

  • 方法3.  引用jQuery插件,$.parseJSON()

语法:

$.parseJSON(json)  //json:String类型,传入格式有误的JSON字符串可能导致抛出异常

$.parseJSON()关键源码分析:

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
$.parseJSON()关键源码

参考:jQuery.parseJSON()方法 | 菜鸟教程jQuery静态方法parseJSON方法使用和源码分析 - -洋仔

 

  • 方法4.  AJAX请求获取JSON数据时,$.getJSON() 

语法:

jQuery.getJSON(url,data,success(data,status,xhr))
//url    必需。规定将请求发送的哪个 URL。
//data    可选。规定连同请求发送到服务器的数据。
//success(data,status,xhr)    可选。规定当请求成功时运行的函数。

这个时候返回的data已经是JSON对象,不需要再进行转换。

$.getJSON() 是简写的 Ajax 函数,等价于:

$.ajax({
url: url,
data: data,
success: callback,
dataType: "json"
});

参考:jQuery ajax - getJSON() 方法

 

 总结:

1.建议使用JSON.parse()方法;如果需兼容IE7/6,再引入json2.js文件。相对应的JSON.stringify()方法,可用来将JSON对象转换为字符串。

2.如果页面里已经引用jQuery,你又不想再引入多余文件(json2.js),也可以使用$.parseJSON()方法。

3.使用eval()时,要注意字符串里没有可执行代码。

4.如果是通过AJAX获取JSON数据,直接用$.getJSON()函数,或者在$.ajax()中加入参数dataType: "json",就可以直接得到JSON对象。

 

 

参考:JS字符串转换为JSON的四种方法笔记 - 天使不哭 - 博客园

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: