How to parse and stringify JSON data

Published on: April 16, 2017

Welcome to the 43rd Easy JavaScript tutorial, part of EasyProgramming.net. We've been working a lot with JSON lately, let's continue by looking at JSON.parse and JSON.stringify. These are two functions that will help you parse a string into a JSON object, and turn an object into a long string. 

When you send data to or receive data from a web server, the data is always in a string format. But there are ways to send entire objects back. You can send it all as a string with JSON.stringify() and use JSON.parse() to parse it back into JSON on your script.

One thing to note is when you're using JSON.parse(), the formatting of the string MUST be in JSON format, otherwise, you will get a syntax error. You cannot parse string that doesn't look like JSON. Let's take a look!

Syntax of JSON.stringify():

    var obj = {
        name: "Nazmus",
        city: "Boston"
    };

    JSON.stringify(obj); //outputs the object as a long string
  

Syntax of JSON.parse():

    var str = '{name: "Nazmus",city: "Boston"}';
    JSON.parse(str); //outputs object version of str
  

To fork the fiddle and follow along: https://jsfiddle.net/easyjs/tf9tk3e3/

Remember to checkout the Resources section below for associated downloadable content, JSFiddle links, and other resources. Watch the video and follow along!

Resources:



Comments: