Languages
[Edit]
EN

JavaScript - convert string to json

8 points
Created by:
JoanneSenior
1070

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}
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.

JavaScript - JSON

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