首页 技术 正文
技术 2022年11月9日
0 收藏 542 点赞 3,077 浏览 3032 个字

  在浏览器前端实现字符串转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()方法;如果需兼容IE6/7,再引入json2.js文件(下载)。 相对应的JSON.stringify()方法,可用来将JSON对象转换为字符串

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

3.使用eval()时,必须保证字符串里没有可执行代码。

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

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903