JSON 데이터 작업하기
이제 JSON 모듈을 올바르게 가져오는 방법을 알았으므로, 일반적인 JSON 작업에 사용하는 방법을 살펴보겠습니다.
완전한 JSON 예제 만들기
다음 내용으로 json_operations.py라는 새 파일을 만듭니다.
## Complete example of working with JSON in Python
import json
## 1. Converting Python object to JSON string (serialization)
user = {
"name": "Charlie",
"age": 28,
"is_student": False,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
## Convert Python dictionary to JSON string
json_string = json.dumps(user, indent=2)
print("JSON string created from Python object:")
print(json_string)
print("\n" + "-"*50 + "\n")
## 2. Parse JSON string to Python object (deserialization)
parsed_user = json.loads(json_string)
print("Python object created from JSON string:")
print("Name:", parsed_user["name"])
print("Age:", parsed_user["age"])
print("Courses:", parsed_user["courses"])
print("City:", parsed_user["address"]["city"])
print("\n" + "-"*50 + "\n")
## 3. Writing JSON to a file
with open("/home/labex/project/user_data.json", "w") as json_file:
json.dump(user, json_file, indent=2)
print("JSON data written to user_data.json")
## 4. Reading JSON from a file
with open("/home/labex/project/user_data.json", "r") as json_file:
loaded_user = json.load(json_file)
print("JSON data loaded from file. User name:", loaded_user["name"])
이 스크립트는 네 가지 일반적인 JSON 작업을 보여줍니다.
json.dumps()를 사용하여 Python 객체를 JSON 문자열로 변환
json.loads()를 사용하여 JSON 문자열을 Python 객체로 구문 분석
json.dump()를 사용하여 JSON 데이터를 파일에 쓰기
json.load()를 사용하여 파일에서 JSON 데이터 읽기
스크립트를 실행합니다.
python3 /home/labex/project/json_operations.py
다음과 유사한 출력을 볼 수 있습니다.
JSON string created from Python object:
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": [
"Python",
"Data Science",
"Web Development"
],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
--------------------------------------------------
Python object created from JSON string:
Name: Charlie
Age: 28
Courses: ['Python', 'Data Science', 'Web Development']
City: Boston
--------------------------------------------------
JSON data written to user_data.json
JSON data loaded from file. User name: Charlie
스크립트는 또한 user_data.json이라는 파일을 생성했습니다. 내용을 살펴보겠습니다.
cat /home/labex/project/user_data.json
적절한 들여쓰기로 형식이 지정된 JSON 데이터를 볼 수 있습니다.
{
"name": "Charlie",
"age": 28,
"is_student": false,
"courses": ["Python", "Data Science", "Web Development"],
"address": {
"street": "123 Tech Lane",
"city": "Boston",
"zipcode": "02101"
}
}
이제 모듈을 올바르게 가져와서 NameError: name 'json' is not defined 오류를 방지하는 방법을 포함하여 Python 에서 JSON 데이터를 사용하는 방법을 성공적으로 배웠습니다.