Posted by Kosal
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:
json
module:The json
module is part of the Python standard library, so you don't need to install any additional packages.
import 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)
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)
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)
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)
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.