Writing JSON to a file

When we write JSON files, we generally do something like this:

from pathlib import Path
with Path("temp.json").open("w", encoding="UTF-8") as target: json.dump(travel3, target, default=blog_j2_encode)

We open the file with the required encoding. We provide the file object to the json.dump() method. When we read JSON files, we will use a similar technique:

from pathlib import Path
with Path("some_source.json").open(encoding="UTF-8") as source:
objects = json.load(source, object_hook=blog_decode)

The idea is to segregate the JSON representation as text from any conversion to bytes on the resulting file. There are a few formatting options that are available in JSON. We've shown you an indent of four spaces because that seems to produce nice-looking JSON. As an alternative, we can make the output more compact by leaving the indent option. We can compact it even further by making the separators more terse.

The following is the output created in temp.json:

{"__class__":"Blog_J","__args__":["Travel",[{"__class__":"Post_J","__args__":[],"__kw__":{"rst_text":"Some embarrassing revelation.","tags":["#RedRanger","#Whitby42","#ICW"],"title":"Hard Aground","date":{"__class__":"datetime.datetime.strptime","__args__":["2013-11-14T17:25:00","%Y-%m-%dT%H:%M:%S"],"__kw__":{}}}},{"__class__":"Post_J","__args__":[],"__kw__":{"rst_text":"Some witty epigram.","tags":["#RedRanger","#Whitby42","#Mistakes"],"title":"Anchor Follies","date":{"__class__":"datetime.datetime.strptime","__args__":["2013-11-18T15:30:00","%Y-%m-%dT%H:%M:%S"],"__kw__":{}}}}]],"__kw__":{}} 

Let's see how to dump and load using YAML.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset