Home > Article > Web Front-end > How to convert json string to object in es6
Conversion steps: 1. Use the JSON.parse() method to convert the json string into an array, the syntax is "JSON.parse(json string)"; 2. Use the expansion operator "..." Just take out the array elements one by one and store them in an empty object "{}", the syntax is "{...array object}".
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
JSON
JSON is a special string format, essentially a string
Like objects and arrays, if the key and value inside are in string format, they are wrapped in double quotes (must be double quotes)
Example:
var jsonStr = '{ "name": "cxh", "sex": "man" }';
es6 method of converting a json string into an object
In es6, you can use arrays and use JSON.parse( ) method and the spread operator "..." to convert json strings into objects.
Conversion steps:
Step 1. Use the JSON.parse() method to convert the json string into an array
JSON.parse() method converts data into JavaScript objects
var jsonStr = '[1,2,3,{"a":1}]'; var arr=JSON.parse(jsonStr); console.log(arr);
Step 2: Use the spread operator "..." Convert an array into an object
The spread operator "..." can expand the array, take out the array elements one by one, and then store them in an empty object "{}".
const obj = {...arr} ; console.log(obj);
[Related recommendations: javascript video tutorial, programming video】
The above is the detailed content of How to convert json string to object in es6. For more information, please follow other related articles on the PHP Chinese website!