Home > Web Front-end > JS Tutorial > How to convert javascript to json string

How to convert javascript to json string

醉折花枝作酒筹
Release: 2021-04-12 10:04:07
Original
3053 people have browsed it

How to convert javascript to json string: 1. Use the "eval()" method, syntax "eval("(" array name")")"; 2. Use "jquery.parseJSON()" Method, syntax "jquery.parseJSON(array name)".

How to convert javascript to json string

The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, Dell G3 computer.

The first way: using the js function eval();

testJson=eval(testJson); is the wrong conversion method.

The correct conversion method requires adding (): testJson = eval("(" testJson ")");

eval() is very fast, but it can compile and execute any javaScript program, so there will be security issues. Using eval(). The source must be trustworthy. Need to use a more secure json parser. If the server does not strictly encode the json or if it does not strictly validate the input, it is possible to provide invalid json or contain dangerous scripts, execute the script in eval(), and release malicious code.

function ConvertToJsonForJs() {
            //var testJson = "{ name: '小强', age: 16 }";(支持)
            //var testJson = "{ 'name': '小强', 'age': 16 }";(支持)
            var testJson = '{ "name": "小强", "age": 16 }';
            //testJson=eval(testJson);//错误的转换方式
            testJson = eval("(" + testJson + ")");
            alert(testJson.name);
        }
Copy after login

The second way: using the jquery.parseJSON() method has relatively high requirements on the format of json and must comply with the json format

jquery.parseJSON()

function ConvertToJsonForJq() {
  var testJson = '{ "name": "小强", "age": 16 }';
  //'{ name: "小强", age: 16 }' (name没有使用双引号包裹)
  //"{ 'name': "小强", 'age': 16 }"(name使用单引号)
  testJson = $.parseJSON(testJson);
  alert(testJson.name);
 }
Copy after login

【Recommended learning: javascript video tutorial

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

Related labels:
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
Latest Issues
What are JavaScript hook functions?
From 1970-01-01 08:00:00
0
0
0
What is JavaScript garbage collection?
From 1970-01-01 08:00:00
0
0
0
c++ calls javascript
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template