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

How to convert string to json in JavaScript

coldplay.xixi
coldplay.xixiOriginal
2021-04-02 11:31:557550browse

How to convert string to json in JavaScript: 1. Use js function [eval();], the code is [testJson = eval("(" testJson ")")]; 2. Use [jquery.parseJSON()] method.

How to convert string to json in JavaScript

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

Method to convert string to json in JavaScript:

The first way:

Use 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 Any javaScript program can be compiled and executed, 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.

js code:

The code is as follows:

  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);
        }

The second method uses the jquery.parseJSON() method, which has higher requirements on the json format and must comply with the json format

jquery.parseJSON()

js: Code

The code is as follows:

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

Related Free learning recommendations: javascript (video)

The above is the detailed content of How to convert string to json in JavaScript. 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