Three ways to convert string to json in js
May 16, 2016 pm 07:28 PMIn the process of developing projects using ajax, it is often necessary to return json format strings to the front end, and the front end parses them into js objects (JSON).
ECMA-262(E3) did not write the JSON concept into the standard. Fortunately, the concept of JSON was officially introduced in ECMA-262(E5), including the global JSON object and Date’s toJSON method. .
1, eval method analysis, I am afraid this is the earliest analysis 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, new Function form, quite weird. The following
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); }
Using JSON.parse must strictly abide by JSON specifications. For example, attributes need to be enclosed in quotation marks, as follows
The code is as follows:
var str = '{name:"jack"}'; var obj = JSON.parse(str); // --> parse error
name is not enclosed in quotation marks , an exception is thrown in all browsers using JSON.parse and parsing fails. The first two methods are fine.
See also: Special implementation of JSON.parse in Chrome
For more related tutorials, please visit JavaScript video tutorial

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Recommended: Excellent JS open source face detection and recognition project

Performance optimization tips for converting PHP arrays to JSON

Detailed explanation of the method of converting int type to string in PHP

How do annotations in the Jackson library control JSON serialization and deserialization?

How to repeat a string in python_python repeating string tutorial

How to check if a string starts with a specific character in Golang?

PHP string manipulation: a practical way to effectively remove spaces

PHP techniques for deleting the last two characters of a string
