¡Hola, Mondo!

Json Data to Go Struct : unmarshal vs decode 본문

Programming/Go

Json Data to Go Struct : unmarshal vs decode

베지(Beji) 2016. 9. 7. 16:46


Json data  -> Struct ( 혹은 interface{} )



: json 데이터를 struct로 변환할 때는 Unmarshal 메소드 혹은 Decode 메소드를 사용한다.




Unmarshal vs Decode


json.Unmarshal

1. byte[] 를 입력으로 가질때
2. 메모리를 효율적으로 사용해야할 때 (Decode 메소드는 전체 json 데이터를 메모리에 버퍼링하기 때문에 비효율적)



decoder.Decode

1. io.reader (file, HTTP request) 를 입력으로 가질때
2. json 데이터가 stream 으로 들어올때 (여러개의 json 데이터 값이 붙어서 들어올때)





JSON Parsing


emp.json

{
   "employees":[
      {
         "firstName":"John",
         "lastName":"Doe"
      },
      {
         "firstName":"Anna",
         "lastName":"Smith"
      },
      {
         "firstName":"Peter",
         "lastName":"Jones"
      }
   ]
}

위와 같은 json 데이터를 파싱하려 할때, decode와 unmarshal 두 메소드를 사용한 코드를 비교한다.



json.Unmarshal


output:
{[{John Doe} {Anna Smith} {Peter Jones}]}


decoder.Decode



output:
{[{John Doe} {Anna Smith} {Peter Jones}]}







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



output:
{[{John Doe} {Anna Smith} {Peter Jones}]}
{[{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{}




output:
map[quick:map[wins:186 lost:172 played:358] competitive:map[played:20 wins:10 lost:10]]
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
Comments