Parsing JSON
Here's a script that parses
JSON data within a string and JSON data found in a file.
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
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)