Python 3-JSON

Python JSON

JSON is a JavaScript Object Notation. JSON is a syntax for storing and exchanging data.

 

JSON in Python

Python has a built-in package called json, which is used to work with JSON data.

Example:

To import the json module:

import json


Parse JSON – Convert form JSON to Python

The JSON string can be parsed using json.loads() method. The result for this would be Python Dictionary.

Example:

Convert from JSON to Python:

import json

# some JSON:
x =  '{ "name":"Mkichael", "age":30, "city":"San Francisco"}'
# parse x:
y = json.loads(x)
# the result is a Python dictionary:
print(y["age"])

Output:

30

 

Convert from Python to JSON

The Python object can convert into a JSON string by using the json.dumps() method.

Example:

Convert from Python to JSON

import json

# a Python object (dict):
x = {
  "name": "Michael",
  "age": 30,
  "city": "San Francisco"
}
# convert into JSON:
y = json.dumps(x)
# the result is a JSON string:
print(y)

Output:

{"name": "Michael", "age": 30, "city": "San Francisco"}

We can also convert Python objects of the following types into JSON objects:

  • dict
  • list
  • tuple
  • string
  • int
  • float
  • True
  • False
  • None

When we convert from Python to JSON, Python objects are converted into JSON equivalent:

Python

JSON

dict

Object

list

Array

tuple

Array

str

String

int

Number

int

Number

True

true

 False

false

None

null


Example 1:

Convert Python objects into JSON strings, and print the values:

import json

print(json.dumps({"name": "Michael", "age": 30}))
print(json.dumps(["apple", "strawberry"]))
print(json.dumps(("apple", "strawberry")))
print(json.dumps("Greetings!"))
print(json.dumps(24))
print(json.dumps(4.67))
print(json.dumps(True))
print(json.dumps(False))
print(json.dumps(None))

Output:

{"name": "Michael", "age": 30}
["apple", "strawberry"]
["apple", "strawberry"]
"Greetings!"
24
4.67
true
false
null

Example 2:

Convert a Python object containing all the legal data types

import json

x = {
  "name": "Michael",
  "age": 30,
  "married": True,
  "divorced": False,
  "children": ("John","Sam"),
  "pets": None,
  "cars": [
    {"model": "Volkswages Pasat", "mpg": 27.5},
    {"model": "Audi 2.5", "mpg": 24.1}
  ]
}
print(json.dumps(x))

Output:

{"name": "Michael", "age": 30, "married": true, "divorced": false, "children": ["John", "Sam"], "pets": null, "cars": [{"model": "Volkswages Pasat", "mpg": 27.5}, {"model": "Audi 2.5", "mpg": 24.1}]}


Format the Result

The above JSON string is very hard to read, with no indentations and line breaks. The json.dumps() method has a parameters to make the JSON string easy to read.

Example:

Use the indent parameter to define the numbers of indents:

json.dumps(x, indent = 4)

Output:

{
    "name": "Michael",
    "age": 30,
    "married": true,
    "divorced": false,
    "children": [
        "John",
        "Sam"
    ],
    "pets": null,
    "cars": [
        {
            "model": "Volkswages Pasat",
            "mpg": 27.5
        },
        {
            "model": "Audi 2.5",
            "mpg": 24.1
        }
    ]
}

The separators has default value (“,”, “:”), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values.

Example:

Use the separators parameter to change the default separator:

print(json.dumps(x, indent = 4, separators=(".","=")))

Output:

{
    "name"="Michael".
    "age"=30.
    "married"=true.
    "divorced"=false.
    "children"=[
        "John".
        "Sam"
    ].
    "pets"=null.
    "cars"=[
        {
            "model"="Volkswages Pasat".
            "mpg"=27.5
        }.
        {
            "model"="Audi 2.5".
            "mpg"=24.1
        }
    ]
}

Order the Result:

The json.dumps() method has a parameter to order the keys in the result.

Example:

Use the sort_keys parameter to specify if the result should be sorted or not:

print(json.dumps(x, indent = 4, sort_keys=True))

Output:

{
    "age": 30,
    "cars": [
        {
            "model": "Volkswages Pasat",
            "mpg": 27.5
        },
        {
            "model": "Audi 2.5",
            "mpg": 24.1
        }
    ],
    "children": [
        "John",
        "Sam"
    ],
    "divorced": false,
    "married": true,
    "name": "Michael",
    "pets": null
}