Home > Web Front-end > JS Tutorial > body text

How to operate json with jquery

coldplay.xixi
Release: 2023-01-04 09:36:58
Original
3327 people have browsed it

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.

How to operate json with jquery

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 = &#39;{"name":"不祥之刃"}&#39;;
    var a = $.parseJSON(jsonStr1);
    console.log("这是一个json对象:",a);
    console.log(a.name);
    var c = $.parseJSON(jsonStr2);
    console.log("这是一个json对象:",c);
    
    //这种方式是错误的
    var jsonStr3 = "{name:&#39;不详之刃&#39;}";    //没有双引号包围起来
    var b = $.parseJSON(jsonStr3);
    console.log(b);
    
</script>
Copy after login

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\":\"张三\"},{&#39;id&#39;:2,&#39;name&#39;:&#39;李四&#39;},{id:3,name:&#39;王五&#39;}]";
    //上面这三种写法不论是用单引号包裹或者双引号包裹或不包裹,都可以用eval解析过来
    var obj = eval(&#39;(&#39;+jsonstr1+&#39;)&#39;);
    console.log(obj);
    console.log(obj[0].name);
Copy after login

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);
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!