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:
xxxxxxxxxx
1
var userObj = JSON.parse('{"id": 2, "name": "Tom", "age": 25}');
2
3
4
// if we don't use JSON.stringify, we get:
5
console.log(userObj); // [object Object]
6
7
// access single json property
8
console.log(userObj.id); // 2
9
console.log(userObj.name); // Tom
10
console.log(userObj.age); // 25
11
12
// when we access undefined json property
13
console.log(userObj.test123); // undefined
14
15
// print json to console
16
console.log(JSON.stringify(userObj)); // {"id":2,"name":"Tom","age":25}
Output:
xxxxxxxxxx
1
[object Object]
2
2
3
Tom
4
25
5
undefined
6
{"id":2,"name":"Tom","age":25}