Introduction to JSON

JSON (JavaScript Object Notation) is a format to represent data, even though it has JavaScript in its name, it is language independent. 

JSON is simply a collection of name/value pairs, In this blog post, we will focus on JSON in JavaScript.

In Javascript, we represent JSON in the form of an object, the key value pairs of an object are enclosed between an opening “{“ and a closing “}” bracket

Example:

var user = {
name: "test",
age: 30,
favorite_color: "blue"
}

In the above example, the variable user contains an object, you can access the objects properties by providing the key of the property as shown below

user.name // returns "test"
user['name'] // returns "test"

As you can see in the above code snippet, there are 2 ways to get a value, by using a dot and by specifying the key in as an index.

JSON.stringify

JSON.stringify is used to convert a JSON object to a string

Example

var user = {
name: "test",
age: 30,
favorite_color: "blue"
}


var user_string = JSON.stringify(user);

You need to use JSON.stringify when using certain API’s like localStorage which cannot store JSON but only strings.

JSON.parse

JSON.parse is used to convert a string representing an object back to an JSON object. Its the reverse of the stringify method.

Example

var user = "{name: 'test', age:30, favorite_color: 'blue'}"

var user_object = JSON.parse(user);

In the above example user is a string (notice the inverted commas around the text),  if you attempt to get the value of name by user.name you will get undefined, to get the value, you need to pass the string to the parse method and then get its value.

Share this!

Leave a Reply

Your email address will not be published. Required fields are marked *