JSON files

In computer science, JSON stands for JavaScript Object Notation. JSON files are what XML files were originally supposed to be. They are often thought of as an “imporvement” on XML files.

Difference between JSON and XML

An XML file looks like this:

<employees>
  <employee>
    <firstName>John</firstName> <lastName>Doe</lastName>
  </employee>
  <employee>
    <firstName>Anna</firstName> <lastName>Smith</lastName>
  </employee>
  <employee>
    <firstName>Peter</firstName> <lastName>Jones</lastName>
  </employee>
</employees>

Notice that in a XML file, the data was covered by some tags. which make the file too long and hard to read. By contrast, a JSON file look like this:

{"employees":[
    {"firstName":"John", "lastName":"Smith"},
    {"firstName":"Anna", "lastName":"Doe"},
    {"firstName":"Peter", "lastName":"Jones"}
]}

In a JSON file, the data was stored as key:value pairs. It’s similar to the format of dictionaies in Python. What’s more, there is a thematic connection with OOP: it’s almost like there is a class called “employees” and we have three objects of that class, and each have two attributes: firstName and lastName.

JSON files have some advantages over XML file. They tend to be shorter and easier to type (because of the lack of “closing tags”). They are automatically compatible with JavaScript, which all computers and web browsers use, and in general are a little easier to run than XML files. They are also in some cases faster to run than XML files. Also, JSON is better for arrays.

A general template for JSON files is:

{
    "array (or python list)": [
        1,
        2,
        3...
    ],
    "boolean": true,
    "color": "gold",
    "null (None in python)": null,
    "number": 123,
    "object (or python dictionary)": {
        "a": "b",
        "c": "d"
    },
    "string": "hello world"
}

To work with JSON format:

  • JavaScript Onject Notation
  • It’s a plain text format
  • Ideal in situtations when we don’t know who will be using our data and what language they might be using (language independent)
  • JSON files can be opened/edited with any text editor
  • Basic foramt of a JSON object is {“key”: value}, just like a dictionary in python
  • Key MUST always be a string with quotation marks (“”)
  • Value can be anything: strings, numbers(int or float), boolean, arrays, other JSON objects, and null (which is None in python)

Create/read JSON file

There is actually a module in python called “json” that allows us to interact with JSON files. In python, to create a basic json file, all we need is a dictionary that we can “dump” into the created file.

# write into a JSON file
import json

my_dict = {"one": 1, "two": 2, "three": 3}
with open("my_json.json", "w") as f:
    json.dump(my_dict, f, indent=2)

Output:

{
  "one": 1,
  "two": 2,
  "three": 3
}

Notice that the JSON file that we made is end with “.json”. In order to write the content of the dictionary into a json file, we need to open this file first using “with open()” in write mode. Within the dump() function, the first argument is the dictionary that we want to “dump”, the second argument is the file stream, and the “indent” argument is used to indent the JSON file to make it easy to read.

To open and read from a JSON file, we can do it in a similar way. But the JSON file needs to exist otherwise an error will be raised.

# read from a JSON file
import json

with open("my_json.json", "r") as f:
    file_content = json.load(f)
    print(file_content)

Output:

{'one': 1, 'two': 2, 'three': 3}

Notice that the content read from a JSON file will be stored in a dictionary, we can access the content by the keys.

From Mozilla: Converting a string to a native object is called deserialization, while converting a native object to a string so it can be transmitted across the network is called serialization.

Addition notes on dump() and load():

The dump() function will write a dictionary into a JSON file, and the load() function will read from a JSON file and store it into a dictionary. While the dumps() function will serialize a dictionary to a JSON formatted string, and the loads() function will turn a JSON formatted string into a dictionary.

Object-oriented programming and JSON file

As the thematic connection with OOP, objects can be encoded and saved in a JSON file. As an instance, we can make a large JSON file that contains a bunch of car object data.

import json

class Car:
    def __init__(self, color, year, make, model):
        self.color = color
        self.year = year
        self.make = make
        self.model = model

D = {}
for i in range(30):
    year = 1990 + i
    D[year] = vars(Car("red", year, "Civic", "Honda"))

with open("car.json", "w") as f:
    json.dump(D, f, indent=2)

Output:

{
  "1990": {
    "color": "red",
    "year": 1990,
    "make": "Civic",
    "model": "Honda"
  },
  "1991": {
    "color": "red",
    "year": 1991,
    "make": "Civic",
    "model": "Honda"
  },
  "1992": {
    "color": "red",
    "year": 1992,
    "make": "Civic",
    "model": "Honda"
  },
  "1993": {
    "color": "red",
    "year": 1993,
    "make": "Civic",
    "model": "Honda"
  },
  "1994": {
    "color": "red",
    "year": 1994,
    "make": "Civic",
    "model": "Honda"
  },
  "1995": {
    "color": "red",
    "year": 1995,
    "make": "Civic",
    "model": "Honda"
  },
  "1996": {
    "color": "red",
    "year": 1996,
    "make": "Civic",
    "model": "Honda"
  },
  "1997": {
    "color": "red",
    "year": 1997,
    "make": "Civic",
    "model": "Honda"
  },
  "1998": {
    "color": "red",
    "year": 1998,
    "make": "Civic",
    "model": "Honda"
  },
  "1999": {
    "color": "red",
    "year": 1999,
    "make": "Civic",
    "model": "Honda"
  },
  "2000": {
    "color": "red",
    "year": 2000,
    "make": "Civic",
    "model": "Honda"
  },
  "2001": {
    "color": "red",
    "year": 2001,
    "make": "Civic",
    "model": "Honda"
  },
  "2002": {
    "color": "red",
    "year": 2002,
    "make": "Civic",
    "model": "Honda"
  },
  "2003": {
    "color": "red",
    "year": 2003,
    "make": "Civic",
    "model": "Honda"
  },
  "2004": {
    "color": "red",
    "year": 2004,
    "make": "Civic",
    "model": "Honda"
  },
  "2005": {
    "color": "red",
    "year": 2005,
    "make": "Civic",
    "model": "Honda"
  },
  "2006": {
    "color": "red",
    "year": 2006,
    "make": "Civic",
    "model": "Honda"
  },
  "2007": {
    "color": "red",
    "year": 2007,
    "make": "Civic",
    "model": "Honda"
  },
  "2008": {
    "color": "red",
    "year": 2008,
    "make": "Civic",
    "model": "Honda"
  },
  "2009": {
    "color": "red",
    "year": 2009,
    "make": "Civic",
    "model": "Honda"
  },
  "2010": {
    "color": "red",
    "year": 2010,
    "make": "Civic",
    "model": "Honda"
  },
  "2011": {
    "color": "red",
    "year": 2011,
    "make": "Civic",
    "model": "Honda"
  },
  "2012": {
    "color": "red",
    "year": 2012,
    "make": "Civic",
    "model": "Honda"
  },
  "2013": {
    "color": "red",
    "year": 2013,
    "make": "Civic",
    "model": "Honda"
  },
  "2014": {
    "color": "red",
    "year": 2014,
    "make": "Civic",
    "model": "Honda"
  },
  "2015": {
    "color": "red",
    "year": 2015,
    "make": "Civic",
    "model": "Honda"
  },
  "2016": {
    "color": "red",
    "year": 2016,
    "make": "Civic",
    "model": "Honda"
  },
  "2017": {
    "color": "red",
    "year": 2017,
    "make": "Civic",
    "model": "Honda"
  },
  "2018": {
    "color": "red",
    "year": 2018,
    "make": "Civic",
    "model": "Honda"
  },
  "2019": {
    "color": "red",
    "year": 2019,
    "make": "Civic",
    "model": "Honda"
  }
}

Leave a Reply

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