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

How to convert string to object in javascript

青灯夜游
Release: 2023-01-04 09:33:59
Original
35157 people have browsed it

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

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)
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!