Jul 17, 2022 iOS

Reading a JSON File in Python: Best Ways to Read JSON File in Python

Reading a JSON File in Python

Every Python coder will encounter situations where they must read a JSON file. So, learning how to read a JSON file is necessary. JSON, which is typically text-based, is used to represent the JavaScript object syntax. JSON is essentially a format for storing or displaying data. Web development and configuration files are two examples of their frequent use cases, and you can use them to transmit data in web applications.

Before reading a JSON file using the Python programming language, import the JSON package into the Python script.  

The Structure of a Basic JSON File

A JSON file has a unique structure that makes it different from others, though you can see them in the same format as dictionaries. Curly braces enclose objects({}), commas separate name-value pairs, and colons separate pairs of names and values ( : ); names in an object are strings.

An example showing a JSON string

‘{“name”:”Emmanuel “, JSON”:28, “car”:null, “sex”:”male” }’

Let’s look at its fundamental structure using an example that shows information from an online store. 

A simple example showing a JSON file: 

data= { 
    "size": 43,
    "price": 58.89,
    "features": ["black", "air sole"],
    "extra_shoe lace":False,
    "delivery":True,
    "client": {
        "name": "Basil Nicole ",
        "phone": +1284567435256,
        "email": "[email protected]"
    }
}

Nitro_json_string = json.dumps(data)
print(Nitro_json_string)

Note: You can use  Json.dumps() to convert a Python object to a JSON string

#Output

{“size”: 43, “price”: 58.89, “features”: [“black”, “air sole”], “extra_shoe lace”: false, “delivery”: true, “client”: {“name”: “Basil Nicole “, “phone”: 1284567435256, “email”: “basil01@11nileshgmail-com}

How to Get Started with Reading a JSON File in Python 

It is essential that you comprehend how a JSON file functions before you begin reading a JSON file in Python. But there is no better way to address this other than by working with a JSON document. 

Receiving data from a web server is one activity you need a JSON file for. Additionally, a JSON file can be used to store files that contain the following:

  • an array
  • a string
  • a number
  • a boolean
  • null

The JSON module is a Python built-in module that gets installed automatically when you install Python. And it includes functions to help you work with JSON files and strings. 

Example 1:

import json

with open('nitro_file.json') as json_file:
    data = json.load(json_file)
    print(data)

For example, suppose you have a JSON file called citizen.json:

{  
    "citizen": {  
        "name": "Basil Nicole ", 
        "sex" : "Male", 
        "Country": "USA"
        "salary": 40000,   
        "married": true,
        "address": "Imaginary Street 149"  
  
import json

with open('citizen.json') as file:
    data = json.load(file)


print(data)

Example 2:

Let’s create JSON data and read it with a data frame through it using pd.Dataframe() methods.

import pandas as pd

data = { 

    "One": { 

        "0": 60, 

        "1": 80, 

        "2": 10, 

        "3": 49, 

        "4": 45, 

        "5": 60

        "6": 50, 

        "7": 60, 

        "8": 45, 

        "9": 45, 

        "10": 23


    }, 

    "Two": { 

        "0": 110, 

        "1": 117, 

        "2": 103, 

        "3": 109, 

        "4": 117, 

        "5": 102, 

        "6": 112, 

        "7": 160, 

        "8": 115, 

        "9": 125, 

        "10": 123

    } 
}  

df = pd.DataFrame(data)   

print(df)

#Output 

      Text Scores  Exam Scores

0            23           50

1            34           59

2            10           63

3            19           49

4            25           37

5            30           69

6            20           62

7            10           70

8            26           64

9            13           45

10           23           69

Note: Ensure the JSON file is saved on your machine with the “.json” extension. You can easily parse a JSON string using the JSON.loads() method.

Reading a JSON File in Python Containing an Array of Objects

In this illustration, JSON content is read from data.json files. The array of objects in the JSON data is;

[
{
    "Gs": 82,
    "Pa": 81,
    "Cx": 99
},
{
    "Td": 58,
    "He": 32,
    "Pf": 83
},
{
    "Yg": 98,
    "Jh": 72,
    "Zi": 93
}
]



import json

fileObj = open("data.json", "r")
jsonfile= fileObj.read()
New_List = json.loads(jsonfile)
print(New_List[2])
print(New_List[0])

#Output

{‘a’: 98, ‘b’: 72, ‘c’: 93}

{‘”Gs”: 82, “Pa”: 81, “Cx”: 99}

Index