[Code]
import json
from json import JSONEncoder
class Student(object):
def __init__(self, rollNumber, name, *args, **kwargs):
self.rollNumber = rollNumber
self.name = name
class StudentEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
student = Student(1, "Emma")
# encode Object it
studentJson = json.dumps(student, cls=StudentEncoder, indent=4)
#Deconde JSON
resultDict = json.loads(studentJson)
print(resultDict)
studentObj = Student(**resultDict)
print(studentObj.rollNumber, studentObj.name)
[Console]
C:\Users\Sion\AppData\Local\Programs\Python\Python37\python.exe G:/untitled/Data.py
{'rollNumber': 1, 'name': 'Emma'}
1 Emma
Process finished with exit code 0
[코드 설명]
- JSON 객체를 가져와서 Dictionary 형태로 바꾸고 포인터 연산자(?)를 통해 매개변수를 던지면
(rollNumbers=1, name="emma") 이런식으로 넘기는 것과 같아지기 때문에 각 매개변수에 매칭하게 된다.
그래서 그걸 토대로 Class의 각 필드값에 매칭되어진다.
가져오기만 할거라면 Encode 부분은 없어도 된다.
'앱 개발자 역량 > Python' 카테고리의 다른 글
Python GUI 비교 및 용도 선정 방법 (0) | 2023.06.12 |
---|---|
Python ] #6 Function (0) | 2019.11.13 |
Python ] #5 Tuple, Dictionary (0) | 2019.11.13 |
Python ] #4 List, Document 확인방법 (0) | 2019.11.12 |
Python ] #3 Variable (0) | 2019.11.12 |