Python 3 comes with a built-in json
module that handles encoding (serializing) and decoding (deserializing) Python data to and from JSON.
dumps()
To encode (serialize) Python data as a JSON string, we can use the built-in json.dumps()
function (the s
at the end of the name stands for "string" as in "dump string"):
1 2 3 4 5 6 7 8 9 10 11 | import json data = { 'str': 'value', 'list': [1, 2, 3, 4], 'dict': { 'a': 'b' }, } data_json = json.dumps( data ) print( data_json ) |
This will output the JSON in a compact format:
{"str": "value", "list": [1, 2, 3, 4], "dict": {"a": "b"}}
We can pretty print the output (make the output more human-readable) by adding indentation and sorting the keys:
1 2 3 4 5 6 7 8 9 10 11 | import json data = { 'str': 'value', 'list': [1, 2, 3, 4], 'dict': { 'a': 'b' }, } data_json = json.dumps( data, indent=4, sort_keys=True ) print( data_json ) |
The output now looks like:
{ "dict": { "a": "b" }, "list": [ 1, 2, 3, 4 ], "str": "value" }
dump()
The examples above stored the JSON output to a string called data_json
. If we want to save the JSON as a file, we could first output to a string and then save it to a file. But the json
module provides us with another function json.dump()
(there is no s
at the end) that lets us do that in one step:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import json data = { 'str': 'value', 'list': [1, 2, 3, 4], 'dict': { 'a': 'b' }, } # Save as mydata-compact.json using json.dump(). with open( 'mydata-compact.json', 'w' ) as json_file: data_json = json.dump( data, json_file ) # Show the file contents on screen. with open( 'mydata-compact.json', 'r' ) as json_file: print( json_file.read() ) |
open( 'mydata.json', 'w' )
opens a file called mydata.json
in the script user's current directory (creating it if it doesn't already exist) for writing text output ('w'
). The file can be referenced by the variable json_file
, which is passed to json.dump()
for writing.
The second argument to json.dump()
doesn't have to be an actual file on the file system — it can actually be any file-like object such as io.StringIO
.
We can use indent
and sort_keys
with dump()
just as we did with dumps()
to pretty print the output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import json data = { 'str': 'value', 'list': [1, 2, 3, 4], 'dict': { 'a': 'b' }, } # Save as mydata-pretty.json using json.dump(). with open( 'mydata-pretty.json', 'w' ) as json_file: data_json = json.dump( data, json_file, indent=4, sort_keys=True ) # Show the file contents on screen. with open( 'mydata-pretty.json', 'r' ) as json_file: print( json_file.read() ) |
We can go the other direction and decode (deserialize / parse) a JSON string using json.loads()
(the s
at the end of the name stands for "string" as in "load string")
1 2 3 4 5 6 7 | import json data_json = '{"str": "value", "list": [1, 2, 3, 4], "dict": {"a": "b"}}' data = json.loads( data_json ) print( data ) |
As with dump()
for encoding, we can decode a JSON file directly using load()
:
1 2 3 4 5 6 | import json with open( 'mydata-compact.json', 'r' ) as json_file: data = json.load( json_file ) print( data ) |