9.5 Serialization with JSON

  • JSON (JavaScript Object Notation) is a text-based, human-and-computer-readable, data-interchange format used to represent objects as collections of name–value pairs.
  • Preferred data format for transmitting objects across platforms.

JSON Data Format

  • Similar to Python dictionaries
  • Each JSON object contains a comma-separated list of property names and values, in curly braces.
    {"account": 100, "name": "Jones", "balance": 24.98}
    
  • JSON arrays, like Python lists, are comma-separated values in square brackets.

    [100, 200, 300]
    
  • Values in JSON objects and arrays can be:

    • strings in double quotes
    • numbers
    • JSON Boolean values true or false
    • null (like None in Python)
    • arrays
    • other JSON objects

Python Standard Library Module json

  • json module enables you to convert objects to JSON (JavaScript Object Notation) text format
  • Known as serializing the data
  • Following dictionary, which contains one key–value pair consisting of the key 'accounts' with its associated value being a list of dictionaries representing two accounts
In [10]:
accounts_dict = {'accounts': [
    {'account': 100, 'name': 'Jones', 'balance': 24.98},
    {'account': 200, 'name': 'Doe', 'balance': 345.67}]}

Serializing an Object to JSON

  • Write JSON to a file
  • json module’s dump function serializes the dictionary accounts_dict into the file
In [11]:
import json
In [12]:
with open('accounts.json', 'w') as accounts:
    json.dump(accounts_dict, accounts)
  • Resulting file contains the following text—reformatted slightly for readability:
    {"accounts": 
    [{"account": 100, "name": "Jones", "balance": 24.98}, 
     {"account": 200, "name": "Doe", "balance": 345.67}]}
    
  • JSON delimits strings with double-quote characters.

Deserializing the JSON Text

  • json module’s load function reads entire JSON contents of its file object argument and converts the JSON into a Python object
  • Known as deserializing the data
In [13]:
with open('accounts.json', 'r') as accounts:
    accounts_json = json.load(accounts)
In [14]:
accounts_json
Out[14]:
{'accounts': [{'account': 100, 'name': 'Jones', 'balance': 24.98},
  {'account': 200, 'name': 'Doe', 'balance': 345.67}]}
In [15]:
accounts_json['accounts']
Out[15]:
[{'account': 100, 'name': 'Jones', 'balance': 24.98},
 {'account': 200, 'name': 'Doe', 'balance': 345.67}]
In [16]:
accounts_json['accounts'][0]
Out[16]:
{'account': 100, 'name': 'Jones', 'balance': 24.98}
In [17]:
accounts_json['accounts'][1]
Out[17]:
{'account': 200, 'name': 'Doe', 'balance': 345.67}

Displaying the JSON Text

  • json module’s dumps function (dumps is short for “dump string”) returns a Python string representation of an object in JSON format
  • Canbe used to display JSON in a nicely indented format
    • sometimes called “pretty printing”
  • When call includes the indent keyword argument, the string contains newline characters and indentation for pretty printing
    • Also can use indent with the dump function when writing to a file
In [18]:
with open('accounts.json', 'r') as accounts:
    print(json.dumps(json.load(accounts), indent=4))
    
{
    "accounts": [
        {
            "account": 100,
            "name": "Jones",
            "balance": 24.98
        },
        {
            "account": 200,
            "name": "Doe",
            "balance": 345.67
        }
    ]
}

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.