EN
JavaScript - convert string to json
8
points
Hi, today I would like to share how we can convert string to JSON using JavaScript.
A lot of programmers by mistake call object created from string (parsing product) as JSON, what is a mistake - read this article.
This article was created only to make it easier to find solution for wrong asked question by programmers. The correct question should be asked: how to convert JSON string to object.
Quick solution:
// ONLINE-RUNNER:browser;
var userObj = JSON.parse('{"id": 2, "name": "Tom", "age": 25}');
// if we don't use JSON.stringify, we get:
console.log(userObj); // [object Object]
// access single json property
console.log(userObj.id); // 2
console.log(userObj.name); // Tom
console.log(userObj.age); // 25
// when we access undefined json property
console.log(userObj.test123); // undefined
// print json to console
console.log(JSON.stringify(userObj)); // {"id":2,"name":"Tom","age":25}
Output:
[object Object]
2
Tom
25
undefined
{"id":2,"name":"Tom","age":25}