【问题标题】:How to format JSON correctly with arrays如何使用数组正确格式化 JSON
【发布时间】:2021-04-24 19:01:45
【问题描述】:

我正在尝试在我的 POST 请求中发送 JSON 有效负载,但我不确定如何正确格式化它以使用数组。下面是正确的 JSON 本身的样子:

{
    "animal": "dog",
    "contents": [{
        "name": "daisy",
        "VAL": "234.92133",
        "age": 3
    }]
}

到目前为止我有这个:

        group := map[string]interface{}{
            "animal": "dog",
            "contents": map[string]interface{}{
                "name": "daisy",
                "VAL":  "234.92133",
                "age":  3,
            },
        }

但我不知道如何处理内容数组(方括号),只有“内容”中的大括号。

【问题讨论】:

  • A Tour of Go了解切片
  • 对于 JSON,结构通常比字符串/接口{}映射更容易和更好。

标签: arrays json http go request


【解决方案1】:

快速回答:

    group := map[string]interface{}{
        "animal": "dog",
        "contents": []map[string]interface{}{
            {
                "name": "daisy",
                "VAL":  "234.92133",
                "age":  3,
            },
        },
    }

但正如 cmets 中已经说过的,最好(类型安全)使用结构来代替:

type Animal struct {
    Type     string          `json:"animal"`
    Contents []AnimalContent `json:"contents"`
}

type AnimalContent struct {
    Name  string `json:"name"`
    Value string `json:"VAL"`
    Age   int    `json:"age"`
}

然后创建:

    group := Animal{
        Type:     "dog",
        Contents: []AnimalContent{
            {
                Name:  "daisy",
                Value: "234.92133",
                Age:   3,
            },
        },
    }

    // to transform to json format
    bts, err := json.Marshal(group)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(bts))

【讨论】:

    猜你喜欢
    • 2023-04-04
    • 2018-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    相关资源
    最近更新 更多