≡ Menu

5 Python Examples to Read and Write JSON files for Encode and Decode

[Python JSON File]

JSON stands for JavaScript Object Notation, which is a format for structuring data that is very similar to the concept of maps in computer programming. Maps consists of keys and corresponding values. A key has to be unique within a map.

JSON is light-weight format of representing data as text in a file, whose syntax is borrowed from the syntax used to create JavaScript Objects. Huge data is converted to JSON format for easy processing in various programming languages and transferring to other nodes. It is most commonly used format for requests and responses while working with API calls.

1. Data Types accepted in JSON Format

JSON keys has to be string. Most of the languages implicitly convert any other data type to string. JSON values can be string, boolean, integer, float, another JSON object or JSON array.

The following is an example of a valid JSON file (data.json):

{
  "name": "Jason",
  "age": 21,
  "address": {
    "street": "1 Main Street",
    "city": "Los Angeles",
    "zipcode": 90001
  },
  "married": false
}

Here, the value of “address” key is another JSON. Key “married” has value of type boolean.

Note that JSON does not support comments. All code snippets given here is also compatible with python 3.

The data type in Python that is closest to JSON is dictionary. Python supports interconversions of dictionary, JSON and string using a module named json, an in-built python library. To learn more about dictionaries, read this article: Python Dictionary Examples – Create, Update and Delete Elements

2. Reading JSON Files

JSON files usually have extension .json. However, python support parsing for any file extension till it contains a valid JSON. To read a json file and populate data into dictionary, json.load() is used. This function takes file object as parameter. Following is an example illustrating the use of json.load()

Example code snippet:

import json

with open("data.json") as f:
    p = json.load(f)
    print(p, type(p))
    print(p["name"], "is", "married" if p["married"] else "not married")

Output for the above example:

{'name': 'Jason', 'age': 21, 'address': {'street': '1 Main Street', 'city': 'Los Angeles', 'zipcode': 90001}, 'married': False} <class 'dict'>
Jason is not married

Here f is the file object. json.load() returns a dictionary.

The above code snippet uses python if else format. Refer to this for additional information: 9 Python if, if else, if elif Command Examples

3. Reading Strings or Byte arrays to Dictionary

Json module allows the user to parse json in the form of strings, bytes or byte array into dictionary. This is done using function json.loads() . Note the similarity in the function name with the previous function described. load() expects a file object as parameter, while loads() expect a string as parameter. The former reads the file and implicitly calls the latter, i.e. loads().

Example code snippet:

import json

with open("data.json") as f:
    file_data = f.read()
p = json.loads(file_data)
print(p, type(p))
print(p["name"], "is", "married" if p["married"] else "not married")

Output for the above example:

{'name': 'Jason', 'age': 21, 'address': {'street': '1 Main Street', 'city': 'Los Angeles', 'zipcode': 90001}, 'married': False} <class 'dict'>
Jason is not married

4. Writing Dictionary to a JSON File

Only strings, byte arrays or bytes can be written to a file. Hence dictionary must be converted to a JSON formatted string to be able to write to a json file. This is done using the function json.dump(). This function takes the dictionary and the file object as parameters. It does not return anything. Following is an illustration of the same.

Example code snippet:

import json

json_dict = {
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": False
}

print("Type of json_dict:", type(json_dict))

with open("data.json", "w") as f:
    json.dump(json_dict, f, indent=4)

Output for the above example:

Type of json_dict: <class 'dict'>

data.json
{
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": false
}

Note that the json file is formatted with tab as 4 spaces. This is in effect due to the “indent” parameter in json.dump() function.

5. Writing JSON Formatted String to a File

In the previous example, parsing on dictionary to string and writing to the file is done using one function, in one statement. Here, that one step is divided into two steps: the dictionary is first converted to a string, saved into a variable and then written to the file.

Example python code snippet:

import json

json_dict = {
    "name": "Jason",
    "age": 21,
    "address": {
        "street": "1 Main Street",
        "city": "Los Angeles",
        "zipcode": 90001
    },
    "married": False
}

print("Type of json_dict:", type(json_dict))

with open("data.json", "w") as f:
    v = json.dumps(json_dict)
    print("v has value", v, "and is of type", type(v))
    f.write(v)

Output for the above example:

Type of json_dict: <class 'dict'>
v has value {"name": "Jason", "age": 21, "address": {"street": "1 Main Street", "city": "Los Angeles", "zipcode": 90001}, "married": false} and is of type <class 'str'>

data.json
{"name": "Jason", "age": 21, "address": {"street": "1 Main Street", "city": "Los Angeles", "zipcode": 90001}, "married": false}

Note that the data.json file is not formatted. This is because the parameter “indent” has been omitted from json.dumps() function.

For extended features of json module, refer to Python JSON documentation.

Add your comment

If you enjoyed this article, you might also like..

  1. 50 Linux Sysadmin Tutorials
  2. 50 Most Frequently Used Linux Commands (With Examples)
  3. Top 25 Best Linux Performance Monitoring and Debugging Tools
  4. Mommy, I found it! – 15 Practical Linux Find Command Examples
  5. Linux 101 Hacks 2nd Edition eBook Linux 101 Hacks Book

Bash 101 Hacks Book Sed and Awk 101 Hacks Book Nagios Core 3 Book Vim 101 Hacks Book