Python Code to Work with JSON Data

JSON is a text format used by websites and APIs to send data. It looks like a Python dictionary. Python has a built-in json module to convert between JSON text and Python objects.

JSON string to Python (json.loads)

import json

data = '{"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}'

user = json.loads(data)

print(user["name"])
print(user["skills"][0])
print(type(user))

Output:

Tutorials Class - Output Window

Robin
Python
<class 'dict'>

Python to JSON string (json.dumps)

import json

user = {"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}

print(json.dumps(user))

Output:

Tutorials Class - Output Window

{"name": "Robin", "age": 25, "skills": ["Python", "SQL"]}

Add indent=2 to json.dumps() to get a nicely formatted text with line breaks.

Save to and load from a file

import json

user = {"name": "Robin", "age": 25}

with open("user.json", "w") as f:
    json.dump(user, f)

with open("user.json") as f:
    loaded = json.load(f)

print(loaded["age"])

Output:

Tutorials Class - Output Window

25

Note: Remember: loads and dumps (with s) work with strings, while load and dump work with files.

Related: Python Dictionary and Python File Handling.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.