Python Module: JSON

Overview

JavaScript Object Notation (JSON) is written in plain-text that is very useful to store objects in a structured format. Python has a module that can parse and update JSON objects. Be mindful that these are two different languages being involved, translating back and forth between Python and JSON can sometimes compromise the integrity of the original objects.

Serialize / Serialization / Marshaling

This is the process of transforming data into series of bytes. In this context, we are referring to the Python dictionaries (objects) being transcoded and written into .json files. Here is a map between language of Python and JSON.

marshall and pickle modules can also serve similar purposes. Usage of those related modules is out of scope of this document.

Python JSON
dict object
listtuple array
str string
intlongfloat number
True true
False false
None null
Deserialization

The reciprocal process is called serialization. Here is that reversal transcoding table:

JSON Python
object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None
dump() function

This takes two positional arguments: (1) the data object to be serialized, and (2) the file-like object to which the bytes will be written.

dumps() function

Unlike dump(), this only takes 1 argument. dump() doesn’t write to disk.

load() function

Deserialize results of an embedded .read()-function, supporting file-like object containing a JSON document to a Python object using the conversion table. Here is the syntax

json.load(open(someFile.json)[, encoding[, cls[, object_hook[, parse_float[, parse_int[, parse_constant[, object_pairs_hook[, **kw]]]]]]]]) 
loads() function

The s stands for string. The json.loads() function does not take the file path, but the file contents as a string. The result shall be a str or unicode instance containing a pointer to JSON document.


Illustrations

Contents of ./dictionary.json


{
"cover": "Paperback"
"pages": 1754
"version": "1.24"
}

Use the keyword ‘with‘ to close session as soon as function goes out of scope. Open a sample JSON object as read-only. alias it as jsonDictionary. parse jsonDictionary contents into parsedDictionary using the loads() function.

with open("./dictionary.json","r") as jsonDictionary:
parsedDictionary = json.loads(jsonDictionary)

Put the contents of the parsed json object’s property into temporary memory.

version = parsedDictionary["version"]

Change value of Python library’s property

parsedDictionary["version"]=1.25

Write back to JSON file (overwrite original)

with open(".\dictionary.json", "w") as jsonDictionary:
json.dumps(parsedDictionary, jsonDictionary)

An alternative to previous function: open as read/write then edit JSON file directly

with open(".\dictionary.json", "r+") as jsonDictionary:
parsedDictionary = json.loads(jsonDictionary)

version = parsedDictionary["version"]
parsedDictionary["version"] = 1.25

jsonDictionary.seek(0) # user seek() method move cursor back to beginning
json.dumps(parsedDictionary, jsonDictionary) # merge the contents of original and parsed objects
jsonDictionary.truncate() # clean up the variance after the merger between parsed and original JSON

How to change the indentation and separator markers of JSON file

import json

library = {
"cover": "Paperback"
"pages": 1754
"version": "1.24"
}

# use . and a space to separate objects, and a space, a = and a space to separate keys from their values:
json.dumps(library, indent=4, separators=(", ", " = "))

Leave a Reply

Your email address will not be published. Required fields are marked *