在浏览器前端实现字符串转 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.JS https://github.com/douglascrockford/JSON-js (JSON 官网 http://www.json.org/ )
<!--[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() | 菜鸟教程 https://www.runoob.com/json/json-parse.html ,json2.JS 简析(个人学习) - 奋斗小小鸟的专栏
方法 3. 引用 jQuery 插件,$.parseJSON()
语法:
$.parseJSON(JSON) //JSON:String 类型, 传入格式有误的 JSON 字符串可能导致抛出异常
$.parseJSON()关键源码分析:
- // Attempt to parse using the native JSON parser first
- if ( Windows.JSON && Windows.JSON.parse ) {
- return Windows.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 的四种方法笔记 - 天使不哭 - 博客园
来源: https://www.cnblogs.com/coolxiaoyi/p/11251765.html