Understanding JSON – Part 2, Reading

In Part 1, we understood what a JSON is and how it can be put to work to transfer data effectively.

In this part, we’ll quickly understand how JSON Array or Objects can be read.

For reading purposes, we’re going to use JavaScript because it doesn’t require any specific library or external code to read it. Here is our sample JSON:

{"trainNumber":12055, "trainName":"DEHRADUN JAN-SHATABDI"}

Using this block of code, we can obtain the values by referring to the key.

const trainJSON = '{"trainNumber":12055, "trainName":"DEHRADUN JAN-SHATABDI"}';
const obj = JSON.parse(trainJSON);

console.log(obj.trainName);
console.log(obj.trainNumber);

By using the JSON.parse(jsonObject), the obj object can now directly access the keys of the trainJSON.

Output:

> DEHRADUN JAN-SHATABDI
> 12055

Below, is an example how to read a JSON Array and further objects in it.

const json = '[
{"trainNumber":12055, "trainName":"DEHRADUN JAN-SHATABDI"},{"trainNumber":12013, "trainName":"ASR SHATABDI"},
{"trainNumber":12005, "trainName":"KALKA SHATABDI"}]';

const array = JSON.parse(json);

// Printing entire object
console.log(array[1]);

// Accessing particular value in an object
console.log(array[2].trainName)

Output:

> Object { trainNumber: 12013, trainName: "ASR SHATABDI" }
> "KALKA SHATABDI"

Regardless of language, JSON can be read in any. But external dependencies or libraries might be required.


Comments

Leave a Reply

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