Story – Python JSON

Once upon a time, Alex had to create a program that reads and writes data in JSON format. Alex was familiar with JSON, but he wanted to learn more about working with JSON in Python. So, Alex decided to explore Python’s built-in JSON module.

Alex opened a new Python script and imported the JSON module. Then, Alex created a dictionary containing some data that they wanted to write to a JSON file.

import json

data = {
    "name": "Alex",
    "age": 25,
    "hobbies": ["reading", "coding", "hiking"],
    "location": {
        "city": "San Francisco",
        "state": "California",
        "country": "United States"
    }
}

Alex wanted to write this data to a file in JSON format, so they used the json.dump() function to convert the dictionary to a JSON string and write it to a file.

with open("data.json", "w") as f:
    json.dump(data, f)

After running the code, Alex checked the data.json file and saw that the data was written in JSON format.

Next, Alex wanted to read the JSON data from the file and convert it back into a Python object. They opened the file and used the json.load() function to read the JSON data and convert it into a Python object.

with open("data.json", "r") as f:
    json_data = json.load(f)

print(json_data)

Alex ran the code and saw that the JSON data was successfully loaded into a Python object.

JSON is a widely used data format for web services and APIs, and it’s common for Python developers to work with JSON data in their projects. Alex was glad to learn about the built-in JSON module in Python, which makes it easy to work with JSON data.

As Alex continued to work on their project, they used the JSON module to write and read data in JSON format, making their code more efficient and effective.