0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Working with JSON in Python

Posted at

Official Doc: https://docs.python.org/3/library/json.html

Import the JSON module:

json_example.py
import json

Convert Python Object to JSON

json_example.py
>>> import json
>>> colors = ["red","green","blue"]
>>> colors_in_json = json.dumps(colors)
>>> colors_in_json
# ["red","green","blue"]

Parse JSON object

json_example.py
>>> import json
>>> capitals_in_json = [{"country":"Vietnam","capital":"Hanoi"},{"country":"France","capital":"Paris"}]
>>> capitals = json.loads(capitals_in_json)
>>> capitals 
# [{"country":"Vietnam","capital":"Hanoi"},{"country":"France","capital":"Paris"}]

Write to .json file

json_example.py
import json
colors = ["red","green","blue"]
with open("colors.json","w") as file:
    json.dump(colors)

Read from .json file

json_example.py
import json
with open("colors.json") as file:
    colors = json.load(colors)
print(colors)
# ["red","green","blue"]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?