JSON Tutorial
JavaScript Object Notation (JSON) is a human readable and very popular format used by web
services, programming languages (including Python) and APIs to read/write data. In this article we
will learn some basic knowledge of JSON and how to use Python to process JSON.
JSON syntax structure:
uses curly braces {} to hold objects and square brackets [] to hold arrays.
JSON data is written as key/value pairs.
A key/value pair consists of a key (must be a string in double quotation marks "" ), followed
by a colon:, followed by a value. For example: “name”:”John”
Each key must be unique.
Values must be of type string, number, object, array, boolean or null
Multiple key/value within an object are separated by commas ,
JSON can use arrays. Arrays are used to store multiple values in a single variable. For
example:
“name”:”John”,
“age”:30,
“cars”:[ “Ford”, “BMW”, “Fiat”]
In the above example, “cars” is an array which contains three values “Ford”, “BMW” and “Fiat”. If
we have a JSON string, we can convert (parse) it into Python by using the [Link]() method,
which returns a Python dictionary:
import json
myvar = '{“name”:”John”,“age”:30,“cars”:[ “Ford”, “BMW”, “Fiat”]}'
parse_myvar = [Link](myvar)
print(parse_myvar["cars"][0])
The result:
Ford
Note:
Python comes with a built-in package called json for encoding and decoding JSON data so we
need to “import json” first
If you want to write a variable in multiple lines or with special characters (including
NEWLINEs, TABs) then you should use triple quotes """ . For example the “myvar” variable
above can be written as follows:
myvar = """
“name”:”John”,
“age”:30,
“cars”:[ “Ford”, “BMW”, “Fiat”]
"""