Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to read json file in Python

Introduction

If you are learning programming, you might have heard about JSON files and how they are used for storing and exchanging data between different systems. JSON stands for JavaScript Object Notation, but don't worry, you don't need to know JavaScript to work with JSON files. JSON is a lightweight and human-readable data format, which makes it an excellent choice for storing and sharing data.

In this blog post, we will learn how to read JSON files in Python. We will start with the basics and gradually build our understanding of JSON and its usage in Python. We will cover the following topics:

  • What is JSON?
  • JSON structure
  • Reading JSON files in Python
  • Working with JSON data in Python

What is JSON?

JSON is a text format that is completely language-independent but uses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

JSON is built on two structures:

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

These are universal data structures; virtually all modern programming languages support them in one form or another. It makes sense that a data format that is interchangeable with programming languages also be based on these structures.

JSON Structure

To understand how to read JSON files in Python, you first need to understand the structure of a JSON file. JSON files have a specific syntax that must be followed to store data in a structured manner. The basic structure of a JSON file consists of the following components:

  • Objects: An object is a collection of key-value pairs enclosed within curly braces {}. The keys are strings, and the values can be any valid JSON data type (string, number, object, array, boolean, or null). Keys and values are separated by a colon :, and multiple key-value pairs are separated by commas ,.
  • Arrays: An array is an ordered collection of values enclosed within square brackets []. Values can be any valid JSON data type. Multiple values in an array are separated by commas ,.
  • Values: A value can be a string, number, object, array, boolean (true or false), or null.

Here's an example JSON file that represents information about a person:

{
  "name": "John Doe",
  "age": 30,
  "is_student": false,
  "courses": ["math", "history", "chemistry"],
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  }
}

In this example, we have an object with five key-value pairs. The keys are name, age, is_student, courses, and address. The values are a string, a number, a boolean, an array, and another object, respectively.

Reading JSON Files in Python

Now that we understand the structure of a JSON file, let's learn how to read a JSON file in Python. Python has a built-in module called json that provides methods for working with JSON data. We will use the json.load() method to read a JSON file.

Here's a step-by-step guide on how to read a JSON file in Python:

  1. Import the json module: First, you need to import the json module, which is included in the Python standard library.

python import json

  1. Open the JSON file: To read a JSON file, you need to open the file in read mode ('r'). We will use the built-in open() function to open the file.

python with open('person.json', 'r') as file:

In this example, we are opening a file named person.json. The with statement is used to ensure that the file is properly closed after performing the file operations.

  1. Read the JSON data: Once the file is open, you can read the JSON data using the json.load() method. This method reads the JSON data and returns a Python object representing the data.

python data = json.load(file)

In this example, the data variable will hold a Python object (a dictionary) representing the JSON data from the person.json file.

Here's the complete code to read a JSON file in Python:

import json

with open('person.json', 'r') as file:
    data = json.load(file)

print(data)

When you run this code, it will read the person.json file and print the Python object:

{
  'name': 'John Doe',
  'age': 30,
  'is_student': False,
  'courses': ['math', 'history', 'chemistry'],
  'address': {
    'street': '123 Main St',
    'city': 'Anytown',
    'state': 'CA',
    'zip': '12345'
  }
}

Notice that the JSON data has been converted to a Python object (a dictionary). The JSON keys are now dictionary keys, and the JSON values are now dictionary values.

Working with JSON Data in Python

Once you have read the JSON data and have it as a Python object, you can access and manipulate the data just like any other Python object. In our example, the JSON data is represented as a dictionary, so we can access its values using dictionary methods and indexing.

Here are some examples of how to work with JSON data:

  • Access a value: To access the value associated with a key, you can use the dictionary indexing operator [] or the get() method.

```python name = data['name'] age = data.get('age')

print(name)  # Output: John Doe print(age)   # Output: 30 ```

  • Modify a value: To modify a value in the JSON data, you can use the dictionary indexing operator [].

```python data['age'] = 31

print(data['age'])  # Output: 31 ```

  • Add a new value: To add a new key-value pair to the JSON data, you can use the dictionary indexing operator [].

```python data['email'] = 'john.doe@example.com'

print(data['email'])  # Output: john.doe@example.com ```

  • Remove a value: To remove a key-value pair from the JSON data, you can use the del statement.

```python del data['address']

print(data) ```

This will remove the address key and its associated value from the JSON data.

  • Loop through the keys and values: To loop through the keys and values in the JSON data, you can use the items() method of the dictionary.

python for key, value in data.items(): print(key, ":", value)

This will print each key and its associated value in the JSON data.

Now that you know how to read JSON files in Python and work with JSON data, you can explore more advanced features of the json module, such as encoding and decoding custom data types, working with JSON streams, and more.

Conclusion

In this blog post, we learned about JSON files and their structure, and how to read JSON files in Python using the json module. We also learned how to work with JSON data in Python by accessing, modifying, adding, and removing values, as well as looping through the keys and values.

With this knowledge, you can now read JSON files and manipulate JSON data in your Python projects. JSON is a widely-used data format, and knowing how to work with it will benefit you in your programming journey.