You can use Python's json module to receive JSON-formatted files and strings as objects such as dictionaries.
Use the json.loads () function.
s = r'{"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}'
print(s)
# {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
d = json.loads(s)
print(d)
# {'A': {'i': 1, 'j': 2}, 'B': [{'X': 1, 'Y': 10}, {'X': 2, 'Y': 20}], 'C': 'Ah'}
print(type(d))
# <class 'dict'>
Use the json.load () function.
with open('/test.json') as f:
print(f.read())
# {"C": "\u3042", "A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}]}
Use the json.dumps () function.
d = {'A': {'i': 1, 'j': 2},
'B': [{'X': 1, 'Y': 10},
{'X': 2, 'Y': 20}],
'C': 'Ah'}
sd = json.dumps(d)
print(sd)
# {"A": {"i": 1, "j": 2}, "B": [{"X": 1, "Y": 10}, {"X": 2, "Y": 20}], "C": "\u3042"}
print(type(sd))
# <class 'str'>
Use the json.dump () function.
d = {'A': {'i': 1, 'j': 2},
'B': [{'X': 1, 'Y': 10},
{'X': 2, 'Y': 20}],
'C': 'Ah'}
with open('/test.json', 'w') as f:
json.dump(d, f, indent=4)
Recommended Posts