Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- Vue.js
- Golangbenchmark
- 리플렉션성능
- GObenchmark
- line챠트
- pprof
- snoflake
- 대역폭측정하기
- Go성능테스트
- Golang디자인패턴
- golang벤치마크
- go리플렉션성능
- vue3
- GO벤치마킹
- golang uuid
- Go디자인패턴
- vue3-chartjs
- Golang부하테스트
- go로드맵
- Golang벤치마킹
- 챠트그리기
- Go벤치마크
- Line차트
- GO부하테스트
- vue3 axios
- vue3 통신
- 디자인패컨
- Iperf3
- Golang성능테스트
- 디자인패턴학습필요성
Archives
- Today
- Total
import ( "코딩", "행복", "즐거움" )
여러 클래스 객체를 json 문자열로 변경하기 본문

여러 클래스 객체를 JSON 문자열로 변환하려면, 먼저 클래스의 인스턴스를 JSON-serializable한 데이터 구조로 변환해야 합니다. 그리고 이를 리스트 또는 딕셔너리와 같은 컨테이너 타입으로 구성하여 JSON 문자열로 직렬화하면 됩니다.
예를 들어, Person 클래스와 Address 클래스를 정의하고, 두 클래스의 인스턴스를 리스트로 구성한 후 JSON 문자열로 변환하는 방법은 다음과 같습니다
import json
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Address:
def __init__(self, city, country):
self.city = city
self.country = country
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
address1 = Address("Seoul", "South Korea")
address2 = Address("Tokyo", "Japan")
people = [person1, person2]
addresses = [address1, address2]
data = {"people": [p.__dict__ for p in people], "addresses": [a.__dict__ for a in addresses]}
json_string = json.dumps(data)
print(json_string)
여기서는 data 변수에 people과 addresses 라는 키(key)를 가진 딕셔너리를 생성합니다. 이 때 people과 addresses는 각각 Person과 Address 클래스의 인스턴스를 가지는 리스트입니다. 이 리스트에서 각 인스턴스의 __dict__ 속성을 가져와 딕셔너리로 구성하면 JSON-serializable한 데이터 구조가 됩니다. 마지막으로 json.dumps() 함수를 사용하여 JSON 문자열로 변환합니다.
이렇게 변환한 JSON 문자열을 파싱할 때에는 json.loads() 함수를 사용하여 딕셔너리로 변환한 후, 필요한 클래스의 인스턴스를 생성하고 딕셔너리의 값을 속성에 할당하면 됩니다.
쉽쥬?
