일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- Windows 10
- maven
- 그래픽카드
- HTML
- ubuntu
- Big-Data
- gns3
- VNC
- Linux
- Python
- 오버워치
- Cisco
- DBMS
- MVC
- apache spark
- Notepad++
- centos
- GTK
- ThingPlug
- Docker
- Apache Metron
- db
- IOT
- 리눅스
- OpenSOC
- django
- golang
- Today
- Total
¡Hola, Mondo!
Json Data to Go Struct : unmarshal vs decode 본문
Json data -> Struct ( 혹은 interface{} )
Unmarshal vs Decode
json.Unmarshal
decoder.Decode
JSON Parsing
emp.json
{
"employees":[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
}
위와 같은 json 데이터를 파싱하려 할때, decode와 unmarshal 두 메소드를 사용한 코드를 비교한다.
json.Unmarshal
decoder.Decode
emp.json
{
"employees":[
{
"firstName":"John",
"lastName":"Doe"
},
{
"firstName":"Anna",
"lastName":"Smith"
},
{
"firstName":"Peter",
"lastName":"Jones"
}
]
}
{
"employees":[
{
"firstName":"Beji",
"lastName":"Kang"
},
{
"firstName":"Ita",
"lastName":"Joo"
}
]
}
위와 같은 json 파일을 파싱하려 할때 혹은 json 데이터가 stream(연속으로)으로 들어올 때는 Decode를 사용한다.
decoder.Decode
{[{Beji Kang} {Ita Joo}]}
struct 대신 Interface{} 사용하기
{
"data": {
"username": "베지밀",
"level": 59,
"games": {
"quick": {
"wins": "186",
"lost": 172,
"played": "358"
},
"competitive": {
"wins": "10",
"lost": 10,
"played": "20"
}
},
"playtime": {
"quick": "44 hours",
"competitive": "4 hours"
},
"avatar": "https://blzgdapipro-a.akamaihd.net/game/unlocks/0x0250000000000776.png",
"competitive": {
"rank": "51",
"rank_img": "https://blzgdapipro-a.akamaihd.net/game/rank-icons/rank-6.png"
},
"levelFrame": "https://blzgdapipro-a.akamaihd.net/game/playerlevelrewards/0x025000000000091D_Border.png",
"star": ""
}
}
다음과 같이 복잡한 Json 데이터를 파싱하려고 할때, Struct를 선언하기 귀찮을 수 있다.
그럴때 Json을 Go의 Struct 형식으로 변환해주는 사이트를 이용하거나(https://mholt.github.io/json-to-go/)
interface{}로 변환할 수 있다.
[https://mholt.github.io/json-to-go] 사이트 이용시 json데이터의 모든 탭이나 공백을 제거하고 사용해야 작동함
interface{}
map[quick:44 hours competitive:4 hours]
map[wins:186 lost:172 played:358]
map[lost:10 played:20 wins:10]
51
'Programming > Go' 카테고리의 다른 글
go tool pprof (0) | 2016.06.30 |
---|---|
Golang 공부 참고 사이트 (0) | 2016.06.10 |
Go Concurrency (0) | 2016.06.10 |
[CentOS] golang , vim-go 설치 (0) | 2016.05.30 |