【问题标题】:Go - constructing struct/json on the flyGo - 即时构建 struct/json
【发布时间】:2015-05-07 15:41:31
【问题描述】:

在 Python 中,可以创建字典并将其序列化为 JSON 对象,如下所示:

example = { "key1" : 123, "key2" : "value2" }
js = json.dumps(example)

Go 是静态类型的,所以我们必须先声明对象模式:

type Example struct {
    Key1 int
    Key2 string
}

example := &Example { Key1 : 123, Key2 : "value2" }
js, _ := json.Marshal(example)

有时只在一个地方需要具有特定模式(类型声明)的对象(结构),而在其他任何地方都不需要。我不想产生许多无用的类型,也不想为此使用反射。

Go 中是否有任何语法糖可以提供更优雅的方式来执行此操作?

【问题讨论】:

    标签: json go syntactic-sugar


    【解决方案1】:

    您可以使用地图:

    example := map[string]interface{}{ "Key1": 123, "Key2": "value2" }
    js, _ := json.Marshal(example)
    

    您还可以在函数内部创建类型:

    func f() {
        type Example struct { }
    }
    

    或者创建未命名的类型:

    func f() {
        json.Marshal(struct { Key1 int; Key2 string }{123, "value2"})
    }
    

    【讨论】:

      【解决方案2】:

      您可以使用匿名结构类型。

      example := struct {
          Key1 int
          Key2 string
      }{
          Key1: 123,
          Key2: "value2",
      }
      js, err := json.Marshal(&example)
      

      或者,如果你准备好失去一些类型安全,map[string]interface{}:

      example := map[string]interface{}{
          "Key1": 123,
          "Key2": "value2",
      }
      js, err := json.Marshal(example)
      

      【讨论】:

        猜你喜欢
        • 2021-10-08
        • 2021-10-24
        • 2021-12-08
        • 2017-12-20
        • 2010-12-16
        • 2019-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多