How to Convert JSON to JavaScript Object

How to Convert JSON to JavaScript Object

JSON (JavaScript Object Notation) has become the de facto serialization format for REST APIs, due to the fact that it's humanly-readable, simple and small in size.

It uses the same notation used to define JavaScript objects, and naturally, it's extremely straightforward to convert between a JSON string and JavaScript objects.

We'll be working with the following JSON string:

const jsonString = '{"author" : "Plato", "name" : "Republic", "releaseYear" : "375BC"}';

Convert JSON String to JavaScript Object

The JSON module offers two methods - stringify(), which turns a JavaScript object into a JSON String, and parse(), which parses a JSON string and returns a JavaScript object.

It's built into the language itself so there's no need to install or import any dependencies:

const book = JSON.parse(jsonString);
console.log('Type: ', typeof book);
console.log('Contents: ', book)

This results in:

Type: object
Contents: 
{
  author:"Plato",
  name:"Republic",
  releaseYear:"375BC"
}

You might be tempted to eval() a string into an object, but be weary of the practice:

const book = eval("(" + jsonString + ")")
console.log('Type: ', typeof book);
console.log('Contents: ', book)

This works just fine:

Type: object
Contents: 
{
  author:"Plato",
  name:"Republic",
  releaseYear:"375BC"
}

However, this method is also susceptible to code injection. eval() will evaluate and execute any arbitrary text that you put in, provided it can be run. If our jsonString was changed to:

const jsonString = 'console.log("Malicious code")';

Then just evaluating it would result in:

const book = eval("(" + jsonString + ")")
// Malicious code

Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

It is ultimately true that JavaScript runs, to a large degree, on the client's machine, on which they can evaluate and run any code they'd like within the browser. However, a major paradigm shift has occured in recent years, and JavaScript is more and more being used on the server-side as well. Even though Code Injection security does ultimately fall on the server-side, since you can't really prevent it on the front-end - there's a chance JavaScript is running on the server-side as well.

Convert JSON String to JavaScript Array

Although you can parse JSON into any arbitrary object - a common data structure into which you'll convert data are arrays. JSON arrays are contained within square brackets, and elements of arrays are separated by commas:

[element1, element2, element3]

An element can be a standalone element, another JSON object or another array, which in turn can contain any of these types as well. Let's take a look at two arrays - a simple one with a few elements, and one that contains several JSON objects:

const simpleArrayJson = '["Java", "Python", "JavaScript"]';
const objectArrayJson = '[{"name": "Java", "description": "Java is a class-based, object-oriented programming language."},{"name": "Python", "description": "Python is an interpreted, high-level and general-purpose programming language."}, {"name": "JS", "description": "JS is a programming language that conforms to the ECMAScript specification."}]';

const simpleArray = JSON.parse(simpleArrayJson);
const objectArray = JSON.parse(objectArrayJson);

console.log(simpleArray);
console.log(objectArray);

This results in:

[
  "Java",
  "Python",
  "JavaScript"
]

[
  {
    name:"Java",
    description:"Java is a class-based, object-oriented programming language."
  },
  {
    name:"Python",
    description:"Python is an interpreted, high-level and general-purpose programming language."
  },
  {
    name:"JS",
    description:"JS is a programming language that conforms to the ECMAScript specification."
  }
]

Conclusion

In this short tutorial, we've taken a look at how to convert a JSON string into a JavaScript object, and remarked at a bad practice that could introduce vulnerabilities in your code.

Last Updated: January 20th, 2022
Was this article helpful?

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

David LandupAuthor

Entrepreneur, Software and Machine Learning Engineer, with a deep fascination towards the application of Computation and Deep Learning in Life Sciences (Bioinformatics, Drug Discovery, Genomics), Neuroscience (Computational Neuroscience), robotics and BCIs.

Great passion for accessible education and promotion of reason, science, humanism, and progress.

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

Want a remote job?

    © 2013-2022 Stack Abuse. All rights reserved.

    DisclosurePrivacyTerms