Files with the extension .json
such as xxx.json
and JSON format data obtained by hitting WebAPI are
It can be used as a dictionary type object on Python.
--In Python, JSON format data can be used as a dictionary type object.
--Use the json
module.
--Use json.load ()
to load the file.
--Use json.loads ()
to read the character string.
--Use json.dumps ()
for writing.
In Python, you need to ʻimport the
json` module in order to use JSON format data.
jsonTest.py
import json
json
moduleTry reading and writing JSON-formatted data using the json
module.
Dictionary-type objects created in Python can be saved in a JSON file by using the json
module.
jsonWrite.py
import json
d = {"name":"ndj", "place":["Qiita", "Twitter", "YouTube"], "age": 25}
with open("ndj.json", mode="w") as f:
d = json.dumps(d)
f.write(d)
ndj.json
{
"name": "ndj",
"place": ["Qiita", "Twitter", "YouTube"],
"age": 25
}
To save a dictionary type object in a JSON format file, use json.dumps ()
You need to convert a dictionary type object to a string type.
Personally, I would like to note that when you do json.dumps ()
, all keys are forcibly converted to string type.
json.dumps ()
forces the key to be converted to a stringwriteJson.py
import json
d = {1:"one", 100:"hundred", 1000:"thousand"}
with open("nums.json", mode="w") as f:
d = json.dumps(d)
f.write(d)
nums.json
{
"1": "one",
"100": "hundred",
"1000": "thousand"
}
The JSON format file saved above can be used as a dictionary type object. Of course, the same applies to JSON format data obtained by hitting WebAPI.
json.load ()
when loading a JSON fileYou can get a dictionary type object by using json.load ()
for the opened file.
readJson.py
import json
d = {}
with open("ndj.json", mode="r") as f:
d = json.load(f)
json.loads ()
to convert a string type object to a dictionary typeIt can be converted to dictionary type as well as using json.load ()
.
readJson.py
import json
s = '{"name": "ndj", "place": ["Qiita", "Twitter", "YouTube"], "age": 25}'
d = {}
d = json.loads(s)
Python official documentation: json
Recommended Posts