The JSON format

  • #1038
  • 01 Jan 2019

What is JSON?

JSON (JavaScript Object Notation) is a format of how data is structured. It's easy to read and write by the programming languages and it's also verry understandable for humans. In short, the format is a collection of key-value pairs which are separated by colons and commas.  Let's look at the example:
 

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     }
 }

 

The "key-value" pairs are separated by colons and new elements are separated by commas. Every "value" can contain many "key-value" pairs so the elements can be nested in each other. 

 

How to wrtie in JSON ?

We write our programs in Python so we'll look at that how json is generated in Python. First of all we need to import the json module.

import json

Then we create an object that will contais our JSON

data = {}

After that we create our first key

data['firstname'] = []

Then the value for this key

data['firstname'] = "John"

In the same name we add the last name.

data['lastname'] = []
data['lastname'] = "Smith"

And here comes the "Address" which is a little bit more complicated but not enough to make the things hard. We can do it in two ways. Let's look at them.

First way: Create new key called  "address" and add key-value pairs to his value. Sounds complicated but it's not.
 

data['address'] = []
data['address'] = {"streetAddress": "21 2nd Street", "city": "New York", "state": "NY", "postalCode": 10021}

That was easy right ? Second way: create another object for your address and add it to the main.

data['address'] = []

myAddress= {}
myAddress["streetAddress"] = []
myAddress["streetAddress"] = "21 2nd Street"
...
(here we repeat the last line for the other key-values)
...
data['address'] = myAddress

And the last thing we had to do is to convert the JSON to string. Why ? Because the string is more easier way to transfer some information. And because it's easier to send it over internet than the sending of object. At the end JSON is only format not a type of object.

json.dumps(data)

 

How to read JSON ?

Reading is more easier even than the writing.

newData = json.loads(data)

That's it! Now, if you want to print some of the elements you just have to write 

print(newData['firstName'])

And that will show you 

"John"

If you want to print all the iformation you can do it like that:

print(newData)

Usually the JSON strings are big, so you don't want to print them all, only some of  their elements.

 

Courses and lessons with this Tutorial

This Tutorial is used in the following courses and lessons

Image for Perfect STEM course. Module 2 - 1D Games with Led strip.
  • 19
  • 0:00
  • 37
Image for Communication and Format of messages
  • 2
  • 0
  • 2
  • 3d_rotation 0