Parsing JSON text
A file-like object that contains
JSON data can be parsed into a
json
object using
load()
.
loads()
is identical to load()
except that the data is contained in a str
, bytes
or bytearray
instance.
This script demonstrates both load()
and loads()
:
import json
#
# Reading json data from a string
#
d = json.loads ('''
{
"foo":{
"42":"forty-two",
"8" :"eight"
},
"bar":[
{"key":"1"},
{"key":"2"},
{"key":"3"},
{"key":"4"}
]
}
''')
print(d['foo']['42']) # forty-two
# -------------------------------
#
# Reading json data from a file
#
json_file=open('file.json')
f=json.load(json_file)
print(f[2][1]) # Yes
print(f[3]['foo']) # word
This is the file that the script reads (file.json
):
[
1,
2,
[ 3, "Yes", 5 ],
{
"one": "number",
"foo": "word"
}
]
Turning Python objects into JSON text
json.dumps(obj)
returns a JSON-string representation of the
object obj
.
json.dump(obj, fs)
writes such a representation into a file that was opened with
open()
.
import json
obj = {
'num': 42,
'txt': 'Hello world',
'lst': [ 1, 2, 3 ],
'dct': { 'k1': 'one', 'k2': 'two'}
}
print(json.dumps(obj))
#
# {"num": 42, "txt": "Hello world", "lst": [1, 2, 3], "dct": {"k1": "one", "k2": "two"}}
with open('dumped.json', 'w') as df:
json.dump(obj, df)