Golang : 動的なjsonを扱う方法

はじめに

JavaScriptphpなどの型のゆるい言語を使い慣れると、Goのオブジェクトの扱い方に戸惑います。たまにGoを使うのですが、そのたびにはまるので、備忘録として当記事を残します。

サンプルコード

  • 扱うjson
{
    "count": 2,
    "hits": [
        {
            "code": "123-4567",
            "address": "XXX県YYY市ZZZ町"
        },
        {
            "code": "987-6543",
            "address": "aaa県bbb市ccc町"
        }
    ]
}
  • json → interface{}
package main

import (
    "encoding/json"
    "log"
)

func main() {
    var jsonBlob = []byte(`{
        "count": 2,
        "hits": [{"code": "123-4567", "address": "XXX県YYY市ZZZ町"}, {"code":"987-6543", "address":"aaa県bbb市ccc町"}]
    }`)
    var data interface{}
    err := json.Unmarshal(jsonBlob, &data)
    if err != nil {
        log.Panic(err)
    }
    log.Printf("%#v", data)
    //→ map[string]interface {}{"count":2, "hits":[]interface {}{map[string]interface {}{"address":"XXX県YYY市ZZZ町", "code":"123-4567"}, map[string]interface {}{"address":"aaa県bbb市ccc町", "code":"987-6543"}}}

    log.Println(data.(map[string]interface{})["count"].(float64))
    log.Println(data.(map[string]interface{})["hits"].([]interface{})[0].(map[string]interface{})["address"].(string))
    log.Println(data.(map[string]interface{})["hits"].([]interface{})[1].(map[string]interface{})["address"].(string))
    // → 2
    //    XXX県YYY市ZZZ町
    //    aaa県bbb市ccc町
}
  • map → json
package main

import (
    "encoding/json"
    "log"
)

func main() {
    var hits []map[string]interface{}
    hit := map[string]interface{}{"code": "123-4567", "address": "XXX県YYY市ZZZ町"}
    hits = append(hits, hit)
    hit = map[string]interface{}{"code":"987-6543", "address":"aaa県bbb市ccc町"}
    hits = append(hits, hit)

    var data map[string]interface{}
    count := 2
    data = map[string]interface{}{"count": count, "hits": hits}

    log.Printf("%#v", data)
    // → map[string]interface {}{"count":2, "hits":[]map[string]interface {}{map[string]interface {}{"address":"XXX県YYY市ZZZ町", "code":"123-4567"}, map[string]interface {}{"address":"aaa県bbb市ccc町", "code":"987-6543"}}}
    bytes, err := json.Marshal(&data)
    if err != nil {
        log.Panic(err)
    }
    log.Println(string(bytes))
    // → {"count":2,"hits":[{"address":"XXX県YYY市ZZZ町","code":"123-4567"},{"address":"aaa県bbb市ccc町","code":"987-6543"}]}
}

参考

https://www.kaoriya.net/blog/2016/06/25/

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です