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

How to convert javascript string to json

coldplay.xixi
Release: 2023-01-04 09:34:22
Original
9118 people have browsed it

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

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

3, use the global JSON object, as follows:

The code is as follows:

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

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!

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