JavaScript - convert string to json

8 points
Created by:

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 mistake - read this article.

This article was created only to make easier to find solution for wrong asked question by programmers. 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(; // 2
console.log(; // 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}


Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!

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.

❤️💻 🙂