Home  >  Article  >  Web Front-end  >  How to convert json to object with Jquery

How to convert json to object with Jquery

WBOY
WBOYOriginal
2022-06-15 10:10:132070browse

在jquery中,可以利用“Jquery.parseJSON()”函数把json转为对象,该函数用于将符合标准格式的的JSON字符串转为与之对应的JavaScript对象,语法为“$.parseJSON(需要解析并转为JS对象的JSON格式字符串)”。

How to convert json to object with Jquery

本教程操作环境:windows10系统、jquery3.6.0版本、Dell G3电脑。

Jquery怎么把json转为对象

$.parseJSON() 函数用于将符合标准格式的的JSON字符串转为与之对应的JavaScript对象。

注意:传入格式有误的 JSON 字符串可能导致抛出异常。例如,下面这些无效的 JSON 字符串:

"{test: 1}"    
//test是属性名称,必须加双引号
"{'test': 1}"    
//test是属性名称,必须用双引号(不能用单引号)
"'test'" 
//test是属性名称,必须用双引号(不能用单引号)
".1" 
//number 必须以数字开头; "0.1" 将是有效的
"undefined"    
//undefined 不能表示一个 JSON 字符串; null可以
"NaN" 
//NaN 不能表示一个 JSON 字符串; 用Infinity直接表示无限也是不允许的

JSON标准不允许"控制字符"如制表符或换行符,例如:

// 多数情况下,它会抛出一个错误,因为JS解析器会将字符串中的\t或\n等转义直接视作字面值,起到Tab或换行的效果。
$.parseJSON('{"testing":"1\t2\n3"}')

正确写法应该如下(使用两个反斜杠,以免被JS解析器直接转义\t或\n):

$.parseJSON('{"testing":"1\\t2\\n3"}')

语法

$.parseJSON( json )

json String类型 需要解析并转为JS对象的JSON格式字符串

示例如下:





123


输出结果:

How to convert json to object with Jquery

视频教程推荐:jQuery视频教程

The above is the detailed content of How to convert json to object with Jquery. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn