JSON Basics For Beginners-With Examples and Exercises

json-beginners-iconWhen sending and receiving data in IOT applications and APIs you will encounter JSON formatted data.

Having a good working knowledge of JSON, and how to create and use JSON data will be very important in developing IOT applications.

The tutorial is split into two sections. The first section we look at creating JSON data and in the second section we look at converting JSON data into JavaScript objects and extracting values from the data.



In this tutorial and Workbook you will learn:

What is JSON (JavaScript Object Notation)?

JSON is a format for encoding data in human readable format for storing and sending over a network.

Although it started in JavaScript it is used in all modern programming languages.

Why it is Used?

JSON is used because it makes it easy to store and transfer JavaScript arrays and objects as text data.

JSON Format Overview

JSON stores data as:

  • key/value pairs
  • Data is separated using commas
  • Text data is enclosed in double quotes
  • Numerical data has no quotes.
  • Arrays are enclosed in square brackets []
  • Objects are enclosed in curly brackets {}
  • The output is a text string

Sending and Receiving JSON Data

Data from devices and sensors in IOT applications is normally sent in JSON format.

So the application program on the sensor has to package the data into a JSON string, and the receiving application has to convert the JSON string into the original data format e.g. object, array etc .

All major programming languages have functions for doing this.

Creating JSON Formatted Data

You can create a JSON string manually but when coding complex data structures in it common to use a JSON editor.

In addition to verify that the encoding is correct it is also common to use a JSON validator.

We will be looking at examples and doing exercises involving both later in this tutorial.

The exercises consist of a worked example(s) and questions to test your understanding.

Create JSON String Examples

Worked Example 1:

Convert the following JavaScript array to JSON.

var names= [“james”, “jake”];

Answer

[“james”, “jake”]

Worked Example 2:

Convert the following JavaScript object to JSON

var power={voltage: 250,current: 12}

Answer:

‘{“voltage”: 250,”current”: 12}’

Note: In JSON numbers do not need quotes

Worked Example 3:

Convert the following JavaScript object to JSON

var power={voltage: “250”,current: “12”};

Answer:

‘{“voltage”: “250”, “current”: “12”}’

Note: This time even though they are numbers they are represented as strings in JavaScript and so they need quotes.

Questions

Answers to all questions are at the end.

Q1 -The following JSON string consists of

‘[{“sensor”: “sensor1”, “temperature”: 22, “humidity”: 80}]’

Is it

  1. An array
  2. An object
  3. An Array inside an object
  4. An object inside and array

Q2– The JSON string consists of:

‘[{“sensor”: “sensor1”, “temperature”: 22, “humidity”: 80},{“sensor”: “sensor2”, “temperature”: 22, “humidity”: 65}]’

Is it

  1. An array with two objects
  2. An object with two arrays
  3. An Array
  4. An object inside and array

Q3 – The JSON string consists of:

‘[{“sensor”: “sensor1″,”temperature”: 24, “humidity”: 69},{“sensor”: sensor2, “temperature”: 22, “humidity”: 65}]’

Is it?:

  1. Valid
  2. Invalid

How to Create Complex JSON Strings Using the Online JSON Editor

You can use the online JSON editor tool for creating more complex JSON structures.

To illustrate how to use the JSON editor Tool we are going to create a JSON string with an array of 3 objects.The objects are:

Object 1 contains the following key/value pairs:

name=John,DOB=1/1/2000,Age=20

Object 2 contains the following key/value pairs:

name=Jim,DOB=21/2/1990,Age=30

Object 3 contains the following key/value pairs: name=Jane,DOB=6/11/1958,Age=61

Video- Using the Online JSON editor

Converting JSON to JavaScript and Extracting Data

Although you can extract data from a JSON string using JSONata the most common method is to convert it to a JavaScript object, and that is what we cover here.

To convert a JSON string to a JavaScript object you use the JSON parse function.

Object= JSON.parse(JSONstring)

Once the JSON data is placed into a JavaScript Object you can now use normal JavaScript methods and functions to extract elements of that data.

We will start using the simple JavaScript object we saw earlier.

Worked Example 1:

var power={voltage: “240”,current: “1”}

To extract the voltage we use either the dot form or the square bracket.

var voltage=power.voltage or

var voltage=power[“voltage”]

Worked Example 2:

var data=[ { sensor: ‘sensor1’, temperature: 21, humidity: 67 },

[{ sensor: ‘sensor2’, temperature: 22, humidity: 62 } ]

This time we have an array of two objects.

So

var sensor= data[0].sensor

Returns sensor1

var sensor= data[1].hunidity

Returns 62

Note: Arrays start at 0

Worked Example 3:

This time we have an object containing an array :

sensor={ results: [ 1, 21, 34, 21 ] }

To access the 2 element in the results array we use:

var r= sensor.results[1]

Using the Node.js Command Line

When working on decoding JSON strings I often find it easier to paste the string into a node.js command line and decode it there.

The examples below show screen shots using the node.js command prompt for converting to and from JSON strings to JavaScript Objects.

JSON And JavaScript

There are two functions that are used for converting data from JavaScript to JSON and from JSON to JavaScript. They are:

  • JSON.stringify(JavaScript object)
  • JSON.parse(JSON string)

Example: JavaScript Array to JSON String

javascript-array-json
Example: JavaScript Object to JSON String

javascript-object-json

Example: JSON to JavaScript

Below shows the JSON strings b and d being converted back to JavaScript.

JSON-JavaScript

 

Answers to Questions

Question 1: D

Question 2: A

Question 2: B – Missing quotes on sensor2.

Summary

JSON is used extensively in web and IOT applications and is a very easy method for storing and transferring complex data as text.

All major programming languages have functions for encoding and decoding JSON data

JSON WorkBook

If you want more practise with working with JSON and JavaScript then you might be interested in my workbook.

Working With JSON and JavaScript in IOT and Home Automation Projects : Beginners Workbook


JSON-WorkBook

Resources

Related Tutorials

Please rate? And use Comments to let me know more

One comment

Leave a Reply

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