Working with JSON in Python

What is JSON?
JSON (Java Script Object Notation) is a subset of the JavaScript programming language dealing with object literal syntax. More in depth information on it can be found HERE.

Example JSON: {    "firstName": "Jane", "lastName": "Doe", "hobbies": ["running", "sky diving", "singing"], "age": 35, "children": [ {            "firstName": "Alice", "age": 6 },        {             "firstName": "Bob", "age": 8 }    ] } It supports primitive types such as strings and numbers, as well as nested lists and objects. Looks a lot like a Python dictionary doesn't it!

The JSON Python module
Python comes with the built-in package we need for encoding and decoding JSON data. We just need to import the module using: import json The process of encoding JSON is often called serialization. This refers to the transofrmation of data into a series of bytes to be stored or transmitted across a network.

Another term often used is marshaling. This term refers to the task of passing objects to remote objects (RMI). To "marshal" an object means to record its state and CodeBase(s) in such a way that when the marshalled object is "unmarshalled", a copy of the original Object is obtained, possibly by automatically loading the class definitions of the Object. This is a more complex topic and won't go into it any further here.

NOTE: CodeBase is information that tells the reciever of Object where the implementation of this object can be found.

Now deserialization is the reciprocal process of decoding data that has been stored or delivered in the JSON standard syntax.

Serializing JSON
When a computer processes a heap of information it will need to take a big ol' data dump. So the json  library has a dump method for writing data to files. There is also a dumps method for writing to a Python string. Simple Python objects are translated to JSON according to this conversion chart: Here is an example of serialization: import json data = { "president": { "name": "Zaphod Beeblebrox", "species": "Betelgeusian" } } with open("data_file.json", "w") as write_file: json.dump(data, write_file) json_string = json.dump(data)
 * 1) Python
 * 1) Python object.
 * 1) Write object to file.
 * 1) Or you can serialize your data by writing it to a native Python str object.

You can also use the indent keyword argument to specify the indentation size for nested structures: json.dumps(data, indent=4)

Another formatting option is the seperators keyword argument. By default this is a 2-tuple of the seperator strings (", ", ": "), but a common alternative for compact JSON is (",", ":").

You can kind more keywords HERE.

Deserializing JSON
In the json library you will find load  and loads for turning JSON encoded data into Python objects.