Tutorial by Examples

import json d = { 'foo': 'bar', 'alice': 1, 'wonderland': [1, 2, 3] } json.dumps(d) The above snippet will return the following: '{"wonderland": [1, 2, 3], "foo": "bar", "alice": 1}'
import json s = '{"wonderland": [1, 2, 3], "foo": "bar", "alice": 1}' json.loads(s) The above snippet will return the following: {u'alice': 1, u'foo': u'bar', u'wonderland': [1, 2, 3]}
The following snippet encodes the data stored in d into JSON and stores it in a file (replace filename with the actual name of the file). import json d = { 'foo': 'bar', 'alice': 1, 'wonderland': [1, 2, 3] } with open(filename, 'w') as f: json.dump(d, f)
The following snippet opens a JSON encoded file (replace filename with the actual name of the file) and returns the object that is stored in the file. import json with open(filename, 'r') as f: d = json.load(f)
The json module contains functions for both reading and writing to and from unicode strings, and reading and writing to and from files. These are differentiated by a trailing s in the function name. In these examples we use a StringIO object, but the same functions would apply for any file-like obje...
Given some JSON file "foo.json" like: {"foo": {"bar": {"baz": 1}}} we can call the module directly from the command line (passing the filename as an argument) to pretty-print it: $ python -m json.tool foo.json { "foo": { "bar...
Let's say we have the following data: >>> data = {"cats": [{"name": "Tubbs", "color": "white"}, {"name": "Pepper", "color": "black"}]} Just dumping this as JSON does not do anything special here: ...
If we just try the following: import json from datetime import datetime data = {'datetime': datetime(2016, 9, 26, 4, 44, 0)} print(json.dumps(data)) we get an error saying TypeError: datetime.datetime(2016, 9, 26, 4, 44) is not JSON serializable. To be able to serialize the datetime object p...

Page 1 of 1