Python JSON Data Handling (Read/Write)
Page Info
Content
Python JSON Data Handling (Read/Write)
In Python, the built-in json
module is used to process JSON data. You can read JSON from files or strings and write Python objects to JSON files or strings.
Reading JSON Data from a File
import json
# Open JSON file in read mode
with open('data.json', 'r', encoding='utf-8') as f:
# Convert JSON data from file to Python object (usually dict)
data = json.load(f)
print(data)
Writing JSON Data to a File
import json
# Python dictionary to save as JSON
data_to_save = {
"name": "John Doe",
"age": 30,
"city": "Seoul"
}
# Open JSON file in write mode
with open('output.json', 'w', encoding='utf-8') as f:
# Convert dict to JSON and write to file
json.dump(data_to_save, f, ensure_ascii=False, indent=4)
print("JSON file has been successfully saved.")
Reading JSON from a String
import json
# JSON string
json_string = '{"name": "Chris Kim", "age": 25, "city": "Busan"}'
# Convert JSON string to Python dictionary
data = json.loads(json_string)
print(data['name']) # "Chris Kim"
print(data['age']) # 25
Converting Python Object to JSON String
import json
# Python dictionary
python_dict = {
"product": "Laptop",
"price": 1200000,
"in_stock": True
}
# Convert Python dict to JSON string
json_output = json.dumps(python_dict, ensure_ascii=False, indent=2)
print(json_output)
# Output:
# {
# "product": "Laptop",
# "price": 1200000,
# "in_stock": true
# }
Key Points
- json.load(): Read JSON from a file and convert it to a Python object.
- json.loads(): Read JSON from a string.
- json.dump(): Write Python object to a JSON file.
- json.dumps(): Convert Python object to a JSON string.
- ensure_ascii=False: Preserves non-ASCII characters.
- indent: Formats JSON output with indentation for readability.
SEO Keywords
Python JSON read write, json.load Python example, json.dump example Python, Python convert dict to JSON, Python parse JSON string, Python JSON file operations
These methods allow you to efficiently read and write JSON data in Python, whether from files or strings, while preserving character encoding and formatting.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.