Languages
[Edit]
EN

JavaScript - convert string to json

8 points
Created by:
JustMike
26150

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

 

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join