JSON For Beginners

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.



In this tutorial you will learn:

  • What JSON is
  • Why it is Used
  • Basic JSON syntax
  • How to use JSON in JavaScript
  • How to use JSON in Python.

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 is is used?

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

JSON Format

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

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)

Examples

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

JavaScript Array to JSON

javascript-array-json

JavaScript Object to JSON

javascript-object-json

JSON to JavaScript

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

JSON-JavaScript

JSON and Python

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

  • json.dumps(Python object)
  • json.loads(JSON string)

Note: The python equivalent of a JavaScript object is a dictionary

Python List to JSON

python-list-json
Python Dictionary to JSON

Python-Dictionary-JSON

JSON to Python

Below shows the JSON strings b and d being converted back to Python objects:

json-python

Where it is Used

Besides being used for transferring data between systems it is also used to configuration files especially in JavaScipt and node.js applications (node-red flows).

The mongo.db database uses JSON to store documents and MYSQL has support for storing JSON objects.

I use JSON in my python and node-red data loggers.

Summary

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

Resources

JSON formatter and Validator

Related Tutorials

Please rate? And use Comments to let me know more
[Total: 1    Average: 5/5]

Leave a Reply

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