WHAT IS PYTHON JSON?

JSON-

Stands for Java Script Object Notation, JSON is an open standard text based data interchange format which is easy for machines to parse and generate.

JSON in python

Python has a built in package called json. json module can be imported in python to work with json data as shown below.

import json

To Convert data from JSON to Python -Parse JSON

We can parse JSON string by using the json.loads() method.

import json
# JSON:
x='{"fruit":"apple", "color":"red"}'
# parse json
y=json.loads(x)
# the result is a Python dictionary:
print(y["fruit"])

output

apple

To convert data from Python to JSON

We can convert Python Object into a JSON string by using theย json.dumps()ย method.

import json

# a Python object (dict):
x = {
  "fruit": "apple",
  "color": "red"
}

# convert into JSON:
y = json.dumps(x)

# the result is a JSON string:
print(y)

Output

{"fruit": "apple", "color": "red"}

We can convert following types of Python objects into JSON strings:

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

On converting the Python to JSON, below table is showing the Python objects converted into the corresponding JSON (JavaScript) equivalent:

PythonJSON
dictObject
listArray
tupleArray
strString
intNumber
floatNumber
Truetrue
Falsefalse
Nonenull

To Format the Result

indent parameter is used to define the number of indent:

import json

# a Python object (dict):
x = {
  "Fruit": "Apple",
  "Color": "Red",
  "Quantity": 12
}

# convert into JSON with indent as 4:
y = json.dumps(x, indent=4)

# the result is a JSON string:
print(y)

Output

{
    "Fruit": "Apple",
    "Color": "Red",
    "Quantity": 12
}

seperators parameter is used to change the default separator value as shown below, ย default value is (“, “, “: “), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:

import json

# a Python object (dict):
x = {
  "Fruit": "Apple",
  "Color": "Red",
  "Quantity": 12
}

# convert into JSON with indent as 4 & seperators(". ", " = "):
y = json.dumps(x, indent=4,separators=(". ", " = "))

# the result is a JSON string:
print(y)

Output

{
    "Fruit" = "Apple". 
    "Color" = "Red". 
    "Quantity" = 12
}

To Sort the Result

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

import json

# a Python object (dict):
x = {
  "Fruit": "Apple",
  "Color": "Red",
  "Quantity": 12
}

# indent parameter will set the indent as 4:
# seperators parameter will change the default seperator values:
# sort_keys parameter will sort or order the results
y = json.dumps(x, indent=4,separators=(". ", " = "), sort_keys=True)

# the result is a JSON string:
print(y)

Output

{
    "Color" = "Red". 
    "Fruit" = "Apple". 
    "Quantity" = 12
}

Posted

in

Tags:

Comments

Leave a Reply