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

How to convert javascript string to json

coldplay.xixi
coldplay.xixiOriginal
2021-04-02 15:59:409167browse

How to convert javascript string to json: 1. Parse in eval mode, the code is [var json = eval('(' str ')')]; 2. New Function form; 3. Use global JSON object.

How to convert javascript string to json

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

How to convert javascript string to json:

1, eval method parsing, I am afraid this is the earliest parsing method. As follows:

The code is as follows:

function strToJson(str){
var json = eval('(' + str + ')');
return json;
}

Remember not to forget the parentheses on both sides of str.

2, the new Function form is quite weird. The following

The code is as follows:

function strToJson(str){
var json = (new Function("return " + str))();
return json;
}

3, use the global JSON object, as follows:

The code is as follows:

function strToJson(str){
return JSON.parse(str);
}

Related Free learning recommendations: javascript (video)

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