In this article, we will understand how to parse a string to a json object in javascript using JSON.parse()
method with example programs and explanation.
String may be a boolean, number, json or an array.
What is JSON
JSON stands for Javascript Object Notation and is a format for transferring data between client and server over a network.
It has gained popularity since it is light weight, structured. It is pretty easy to loop over a json object, get data and update values into it.
JSON Object
JSON object contains key-value pairs where a value may be a single value such as a string, number, boolean or may be a javascript object or an array.
Example of a JSON object is
{ "model": "iphone", "manufacturer": "Apple", "type": "smartphone", "spec": { "ram": "4GB", "hdd": "128GB", "dualcamera": true } }
A JSON object is enclosed between curly braces with key and value separated by a colon(:). Multiple key-values are separated by a comma(,).
In above example, the JSON object contains another JSON object as a value for one of its key. This is also called nested JSON object.
JSON Array
A JSON object can also contain an array as a value for a key as shown below.
{ "device":"smartphone", "brand":"Apple", "colors": ["White", "Silver", "Black"] }
An array begins and ends with a square bracket.
Data returned from server is always in string format. Getting values from a string or iterating over a string is not straight forward.
Nowadays, mostly the data returned from servers is a string in json format. To use it easily, it is convenient to convert it to a JSON object.
Javascript provides an inbuilt object JSON
which has a parse()
method. This method accepts a string in JSON format, parses it and returns a JSON object. Example,
// json string const sm = '{ "model": "iphone", ' + '"manufacturer": "Apple",' + '"type": "smartphone" }'; // convert to JSON object const jsonObj = JSON.parse(sm); // print its type console.log(typeof jsonObj); // prints object
Values from this JSON object can be accessed using their keys using
- dot notation as
jsonObj.key
, or - enclosing the name of key between square brackets and quotes as
jsonObj['key']
.
// json string const sm = '{ "model": "iphone", ' + '"manufacturer": "Apple",' + '"type": "smartphone" }'; // convert to JSON object const jsonObj = JSON.parse(sm); console.log(jsonObj.model); console.log(jsonObj['type']);
This example will print
iphone
smartphone
Json.parse() with nested json object
A JSON object may contain another JSON object.
To get a value from nested object, we need to first access the nested object using its key and then the inner value from this object with the given key. Example,
const sm = '{' + '"model": "iphone",' + '"manufacturer": "Apple",' + '"type": "smartphone",' + '"spec": {' + '"ram": "4GB",' + '"hdd": "128GB",' + '"dualcamera": true' + '}' + }'; const jsonObj = JSON.parse(sm); console.log(sm.spec.ram); console.log(sm.spec['hdd']);
Above code gets the nested JSON object using its key and then inner values with their keys. It prints
4GB
128GB
Once a string is converted to a JSON object, it can be iterated using a javascript for-in loop as shown below.
In every iteration, the loop variable contains a key for JSON object.
const sm = '{' + '"model": "iphone",' + '"manufacturer": "Apple",' + '"type": "smartphone",' + '"spec": {' + '"ram": "4GB",' + '"hdd": "128GB",' + '"dualcamera": true' + '}' + '}'; const jsonObj = JSON.parse(sm); // loop object loopJSONObject(jsonObj); // function to loop json object function loopJSONObject(jsonObj) { for(let key in jsonObj){ // print key console.log('Key: '+key); // check if value is a json object if(typeof jsonObj[key] == 'object') { console.log('------ Nested Object -----'); loopJSONObject(jsonObj[key]); } else { // print value console.log('Value: '+jsonObj[key]); } } }
Above example iterates over the JSON object.
Iteration logic is written in a recursive function(which calls itself). It checks if the value is an object which means that it should also be iterated and calls itself. If the value is not an object, then it is simply printed.
If your JSON object does not contain nested objects, then there is no need of recursive function.
Output is
Key: model
Value: iphone
Key: manufacturer
Value: Apple
Key: type
Value: smartphone
Key: spec
—— Nested Object —–
Key: ram
Value: 4GB
Key: hdd
Value: 128GB
Key: dualcamera
Value: true
String to array
JSON.parse()
method can be used to convert an array in string format to an actual array. As stated before, values returned from server are always in string format.
Thus, if server sends an array to the client, it will be in string format and you can not access its items or iterate over it directly, it needs to be converted to a javascript array. Example,
// convert string to array const arr = JSON.parse('["a", 1, "true"]'); // check the type of converted object console.log(typeof arr); // access third item console.log(arr[2]);
This prints
object
true
Look at the type of parsed value and how it is being used to access the value at third position. This is the same as array values are accessed.
When using
JSON.parse()
, following mistakes should be avoided
1. String to be parsed should not end with a comma. Thus, below code will be an error.
JSON.parse('{ "a" : 1, }');
2. Do not use single quotes around JSON keys or values. Below is an invalid JSON string.
JSON.parse("{ 'a' : 1 }");
Browser Compatibility
JSON.parse()
is supported on below browser versions.
Browser | Version |
---|---|
Chrome | 3 |
Firefox | 3.5 |
Edge | 12 |
IE | 8 |
Safari | 4 |
Opera | 10.5 |
Click the clap button below if the article was useful.