Camkode
Camkode

How to Work with JSON Data in Python

Posted by Kosal

How to Work with JSON Data in Python

Working with JSON (JavaScript Object Notation) data in Python is a common task, as JSON is a popular data interchange format. Python provides a built-in module called json to handle JSON data. Here's a basic guide on how to work with JSON data in Python:

Import the json module:

The json module is part of the Python standard library, so you don't need to install any additional packages.

import json

Converting Python Objects to JSON:

You can use the json.dumps() function to convert a Python object (such as a dictionary, list, or string) to a JSON-formatted string.

# Example with a dictionary
data = {
    "name": "Kosal",
    "age": 32,
    "city": "Phnom Penh"
}

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

Writing JSON to a File:

If you want to save the JSON data to a file, you can use the json.dump() function.

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

Reading JSON from a File:

To load JSON data from a file, you can use the json.load() function.

with open("mydata.json", "r") as json_file:
    loaded_data = json.load(json_file)
    print(loaded_data)

Converting JSON to Python Objects:

If you have a JSON string and you want to convert it back to a Python object, you can use the json.loads() function.

json_string = '{"name": "Kosal", "age": 32, "city": "Phnom Penh"}'
loaded_data = json.loads(json_string)
print(loaded_data)

Handling JSON Data in APIs:

When working with web APIs, you often receive JSON data in response. You can use the requests library to make API requests and then parse the JSON response.

import requests

url = "https://api.mydomain.com/data"
response = requests.get(url)

if response.status_code == 200:
    api_data = response.json()
    print(api_data)
else:
    print(f"Failed to fetch data. Status code: {response.status_code}")

These are the basic steps for working with JSON data in Python. The json module provides more advanced options, such as custom encoding and decoding functions, but these basics should cover most use cases.