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

How to convert string to object in javascript

青灯夜游
青灯夜游Original
2021-04-01 16:06:4735395browse

In javascript, you can use the "JSON.parse()" method to convert a string into an object. This method can parse a string (written in JSON format) and return a JavaScript object, the syntax format is " JSON.parse(string)".

How to convert string to object in javascript

The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.

javascript string to object

Example:

Parse a string (written in JSON format) and return a JavaScript object:

var obj = JSON.parse('{"firstName":"John", "lastName":"Doe"}');
console.log(obj);

Output:

How to convert string to object in javascript

JavaScript JSON.parse() method

JSON.parse() method parsing String and returns a JavaScript object. The string must be written in JSON format. The JSON.parse() method can optionally use a function to convert the result. [Recommended learning: js basic tutorial]

Grammar

JSON.parse(string, function)

Parameter value

Parameter Description
string Required. A string written in JSON format
function Optional. Function used to convert the result. This function is called for each item. Convert any nested objects before their parent.
  • If the function returns a valid value, the item value is replaced with the converted value
  • If the function returns undefined, the item is deleted

Return value: JSON object or array

For more programming-related knowledge, please visit: Programming Video! !

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