Python Read, Write, Parse JSON (with examples)

JSON, Javascript Object Notation, is a lightweight data interchange format inspired by Javascript object literal syntax.

In this article, you’ll learn how to work with JSON data in Python.

Python has a built-in package called json, which can be used to encode and decode json data.

Python JSON encoding/marshaling

Python’s json.dumps() function allows you to serialize or encode a Python type like dict, list, etc; to json string. Here is how you can use it -

import json

user = {
  "name": "Rajeev Singh",
  "age": 26,
  "hobbies": ["Coding", "Travelling", "Photography"],
  "address": {
    "city": "Bangalore",
    "state": "Karnataka",
    "country": "India"
  }
}

jsonData = json.dumps(user)

print(jsonData)
# Output
{"name": "Rajeev Singh", "age": 26, "hobbies": ["Coding", "Travelling", "Photography"], "address": {"city": "Bangalore", "state": "Karnataka", "country": "India"}}

Python JSON decoding/parsing

You can decode a JSON string in Python using the json.loads() function -

import json

jsonData = '{"name": "Sachin Tendulkar", "age": 34, "hobbies": ["Cricket", "Badminton"], "address": {"city": "Mumbai", "state": "Maharastra", "country": "India"}}'

user = json.loads(jsonData)

print(user)
# Output
{'name': 'Sachin Tendulkar', 'age': 34, 'hobbies': ['Cricket', 'Badminton'], 'address': {'city': 'Mumbai', 'state': 'Maharastra', 'country': 'India'}}