Languages

JavaScript - JSON.stringify() reverse

0 points
Asked by:
user4838
728

When I'm stringyfing an object like:

var object = { id: 2, name: 'Tom', age: 25 };

I get:

var jsonString = '{"id": 2, "name": "Tom", "age": 25}';

But how can I turn the jsonString back to an object?

1 answer
0 points
Answered by:
user4838
728

The method you are looking for is JSON.parse().

Practical example

// ONLINE-RUNNER:browser;

var jsonString = '{"id": 2, "name": "Tom", "age": 25}';

try {
    var object = JSON.parse(jsonString);
} catch (e) {
    console.error(e);
}

console.log(object.id);   // 2
console.log(object.name); // Tom
console.log(object.age);  // 25

Note:

Put JSON.parse() into try-catch block, as the method can crash your code.

 

See also

  1. ❤ 💻 JavaScript - parse json - Dirask

References

  1. JSON.parse() - JavaScript | MDN
0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join