Working with JSON in Python


To work with JSON in Python, we need to import the json module:

 import json

To parse JSON to Python Object

We can use json.loads() method as follow:

import json

# some JSON:
x =  '{ "name":"", "age":30, "city":"New York"}'

# parse x:
y = json.loads(x)

# the result is a Python dictionary:

To dumps Python object to JSON

We can use json.dumps() method as follow:

import json

# a Python object (dict):
x = {
  "name": "",
  "age": 30,
  "city": "New York"

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

# the result is a JSON string:

Happy coding!