How to operate json with jquery: 1. Use the [$.parseJSON()] method in jquery; 2. Use eval in js to force transfer; 3. Use the browser’s own [JSON.parse( )】method.
The operating environment of this tutorial: windows7 system, jquery3.2.1 version, thinkpad t480 computer.
Recommended: jquery video tutorial
How to operate json with jquery:
The first method:Use $.parseJSON()
in jquery, but it has higher requirements for json data format and must be surrounded by double quotes
<script type="text/javascript"> //第一种:使用jquery中自带的$.parseJSON()函数 var jsonStr1 = "{\"name\":\"盖伦\"}"; var jsonStr2 = '{"name":"不祥之刃"}'; var a = $.parseJSON(jsonStr1); console.log("这是一个json对象:",a); console.log(a.name); var c = $.parseJSON(jsonStr2); console.log("这是一个json对象:",c); //这种方式是错误的 var jsonStr3 = "{name:'不详之刃'}"; //没有双引号包围起来 var b = $.parseJSON(jsonStr3); console.log(b); </script>
The second method: Use eval in js to force transfer
The advantage is that the json format requirements are not so strict, but it is not good when processing complex json data, such as objects containing objects
//第2种:js里的方法使用eval来解析jason字符串 var jsonstr1="[{\"id\":\"1\",\"name\":\"张三\"},{'id':2,'name':'李四'},{id:3,name:'王五'}]"; //上面这三种写法不论是用单引号包裹或者双引号包裹或不包裹,都可以用eval解析过来 var obj = eval('('+jsonstr1+')'); console.log(obj); console.log(obj[0].name);
The third method: Use the JSON.parse() that comes with the browser
Like jquery, it has higher requirements for json format
//第3种:使用浏览器自带的JSON.parse var jsonStr="{\"id\":\"4\",\"name\":\"王五\"}"; var obj = JSON.parse(jsonStr); console.log(obj);
Related free learning recommendations: javascript(Video)
The above is the detailed content of How to operate json with jquery. For more information, please follow other related articles on the PHP Chinese website!