This article mainly introduces the conversion between js objects and JSON strings in JavaScript, which has some reference value. If you are interested, you can refer to it. This article mainly introduces the conversion between js objects and JSON strings in JavaScript, which has some reference value. If you are interested, you can refer to it.
First, let's take a look at the JSON format strings in js.
Var JSONStr1 = "{\" name \ ": \" Zhang San \"}";
Note that the following statement is not a JSON string in js, but a js string.
Var JSONStr2 = "{'name': 'zhang san '}";
Let's look at the definition of strings in JSON Syntax:It is a set of any number of Unicode characters enclosed by double quotation marks and is escaped using a backslash. A character (character) is a separate string (character string ).
Next let's take a look at how to convert a JSON string into a js object in JS. (
var jsObj3 = eval("(" + JSONStr1 + ")");var jsObj4 = JSON.parse(JSONStr1);
For details about the second method, refer :#
In addition, the js object converted using the two methods should be "a js object conforming to the JSON data format", that is, its attribute is enclosed by quotation marks, this is just my guess, because if the JSON Format String is as follows:
Var JSONStr1 = "{\" f [name] \ ": \" Zhang San \"}";
The attributes of the converted JS object must be enclosed by quotation marks, because the attributes of the js object can only be represented by letters, numbers, underscores, and $ characters without quotation marks, when using other symbolic attributes, quotation marks are required. Therefore, adding quotation marks to attributes in the literal representation of a JS object will not be wrong. In addition, if the JSON string is as shown in the preceding figure, then the converted js object cannot use jsObj4.f [name] to use jsObj4 ['f [name] '] For the f [name] value. note this because of the special characters. If you have any objection to my guess, you can raise it to me.
Let's take a look at the conversion between js objects and JSON strings in js. Below I have prepared several sets of js objects for illustration: