DEV Community

Cover image for How to convert a JSON string into a JavaScript object and vice versa
Zakaria Haruna
Zakaria Haruna

Posted on

How to convert a JSON string into a JavaScript object and vice versa

Are you a beginner starting your web development journey and feeling overwhelmed by the information you're receiving?

Well, all these feelings are normal as you are now being exposed to information that wasn't in your normal daily life. Many people get overwhelmed when they start their coding journey, and it is now the norm for every beginner to experience this kind of feeling.

In this article, I'm going to show you how to convert a JSON string into a JavaScript object and vice versa, as this is going to be a normal thing for you as a web developer.

Web developers often work with a lot of data when building a project, and most of this data can be third-party data, that is, data acquired from external sources, which are mostly in JSON(Javascript Object Notation) form and before and anyone can used this in the project there is the need to convert it into javascript object.

To convert a JSON to a JavaScript object, you have to follow these steps;

JSON string to JavaScript object

Assuming you have the following JSON string: {"fname": "John", "lname": "Mike", "gender": "Male", "country": "Ghana"}
You have to assign it to a variable the same way you do when you are assigning a normal JavaScript variable. So let us do it in code


const jsonStr = `{"fname": "John", "lname": "Mike", "gender": "Male", "country": "Ghana"}`;

const jsObj = JSON.parse(jsonStr);

Enter fullscreen mode Exit fullscreen mode

The above code will change jsonStr, which is a JSON string, into a JavaScript object jsObj.

JavaScript object to JSON string

Now let us look at the other way round, that is, changing a JavaScript object into a JSON string. Let us use the above example by changing the jsObj back to a JSON string, let's code.


JSON.stringify(jsObj);

Enter fullscreen mode Exit fullscreen mode

With the above code, your JavaScript object will be converted into a JSON string.

Conclusion

So, sum everything up, we were able to use the built-in JavaScript parse() and stringify() methods to change a JSON string to a JavaScript object and vice versa.
If you find this post helpful the like and comment, and you can also follow me on GitHub

Top comments (0)