LoginSignup
22
14

More than 5 years have passed since last update.

Go言語でJSONの生成を構造体無しでJavaScript並に簡単に生成できる方法

Last updated at Posted at 2016-11-27

こんにちはnasustです。

Go言語 / golangのJSONの生成はJavaScript並に簡単にできます。
JSONの生成の紹介が構造体しか無かったので、mapで簡単に出来ることを解説します。

json.Marshalで与えられる型でmap[string]interface{}を標準でサポートしています。ですので下記のコードのようにJavaScript並に簡単にJSONを生成できます。

package main

import (
    "encoding/json"
    "fmt"
)

type M map[string]interface{}
type A []interface{}

func main() {
    values := M{
        "a": "a",
        "b": func() A {
            return A{1, 2, 3}
        }(),
        "c": A{"va", "vb", "vc"},
        "d": M{
            "dd": 1.1,
            "cc": 2.2,
            "ee": nil,
            "qq": true}}

    bytes, err := json.MarshalIndent(values, "", "    ")
    if err == nil {
        jsonstring := string(bytes)
        fmt.Println(jsonstring)
    } else {
        fmt.Println("Err: ", err)
    }

}

結果

{
    "a": "a",
    "b": [
        1,
        2,
        3
    ],
    "c": [
        "va",
        "vb",
        "vc"
    ],
    "d": {
        "cc": 2.2,
        "dd": 1.1,
        "ee": null,
        "qq": true
    }
}
22
14
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
22
14