JSON dumps
-
dumps
-
Dictionaries and lists are handles
-
Tuples are indistinguishable from lists
-
Always Double-quotes
-
null
instead ofNone
-
No trailing comma
import json
data = {
"fname" : 'Foo',
"lname" : 'Bar',
"email" : None,
"children" : [
"Moo",
"Koo",
"Roo",
],
"fixed": ("a", "b"),
}
print(data)
json_str = json.dumps(data)
print(json_str)
with open('data.json', 'w') as fh:
fh.write(json_str)
{'fname': 'Foo', 'lname': 'Bar', 'email': None, 'children': ['Moo', 'Koo', 'Roo'], 'fixed': ('a', 'b')}
{"fname": "Foo", "lname": "Bar", "email": null, "children": ["Moo", "Koo", "Roo"], "fixed": ["a", "b"]}
dumps
can be used to take a Python data structure and generate a string in JSON format. That string can then be saved in a file,
inserted in a database, or sent over the wire.