LoginSignup
3
3

More than 3 years have passed since last update.

【Golang】配列や項目がネストされているJsonをmapで取り出す

Posted at

概要

Golangで文字列のJsonから、値取り出す場合、golang で JSON を扱うサンプルの通り、structかmapで取り出す方法が挙げられます。特に、外部のAPIからデータを取得するときは不要な項目が多いので、structを定義するのが面倒ということもあり、mapで必要な項目のみ抜き出したいというふうになると思います。
mapで取り出すとき、配列やネストされている項目をどう取り出すのか、メモ書きします。

参考

golang は ゆるふわに JSON を扱えまぁす!の記事を参考に、サンプルコードを書きました。また、この記事を書いた方はmapでの取り出しを楽にするライブラリgo-dproxyも公開されています。

読み込むコードJson

sample.json

{
  "result": [
    {
      "id": "test1",
      "name": "name1",
      "url": {
        "blog": "http://www.example1.com/"
      }
    },
    {
      "id": "test2",
      "name": "name2",
      "url": {
        "blog": "http://www.example2.com/"
      }
    }
  ]

サンプルコード

jsonReadSample.go

// JSONReadSample Jsonの文字列をmapで読み込んで項目を出力
func JSONReadSample(jsonStr string) {
    var jsonMap map[string]interface{}
    // map形式でJsonをUnmarshal
    json.Unmarshal([]byte(jsonStr), &jsonMap)
    // 配列項目の読み込み
    resultList := jsonMap["result"].([]interface{})
    for _, r := range resultList {
        println(r.(map[string]interface{})["id"].(string))
        println(r.(map[string]interface{})["name"].(string))
        // ネスト項目の読み込み
        println(r.(map[string]interface{})["url"].(map[string]interface{})["brog"].(string))
    }
}

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3