包含字符串和整数的 Golang 映射

Har*_*rry 11 json types marshalling go

我正在尝试使用 golang 中的 JSON.Marshal() 从地图创建 JSON 字符串。但是,int 值显示为用双引号括起来的字符串。

我的代码输出:

{ "age":
    {
        "$gt":"22",
        "$lt":"20"
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
Run Code Online (Sandbox Code Playgroud)

代替

{ "age":
    {
        "$gt":22,
        "$lt":20
    },
  "location":
    {
        "$eq":"london"
    },
  "name":{
        "$eq":"fred"
    }
}
Run Code Online (Sandbox Code Playgroud)

我在用:

var output_map = map[string]map[string]string{}

//Populate map here

output_json, err := json.Marshal(output_map)

if err!= nil {
    fmt.Println("Error encoding JSON")
}

fmt.Println(output_json)
Run Code Online (Sandbox Code Playgroud)

我的理解是,如果提供了整数,JSON.Marshal() 将正确打印整数,但我的地图不会包含整数。我可以将地图更改为map[string]map[string]int{},但它不会包含“name”和“location”的字符串值。

最终的问题是我需要映射包含 int 和 string 值。某种地图[字符串]地图[字符串]{}。

我怎样才能实现这个目标?先感谢您。

哈利

mae*_*ics 8

如果您无法使用正确类型的结构来描述数据,请考虑使用具有类型值(本质上是任何类型)的映射interface{}

output_map := map[string]map[string]interface{}{}
Run Code Online (Sandbox Code Playgroud)

例如:

output_map := map[string]map[string]interface{}{
  "age": {
    "$gt": 18,
  },
  "location": {
    "eq": "London",
  },
}
bytes, err := json.MarshalIndent(&output_map, "", "  ")
if err != nil {
  panic(err)
}
// {
//   "age": {
//     "$gt": 18
//   },
//   "location": {
//     "eq": "London"
//   }
// }
Run Code Online (Sandbox Code Playgroud)

当然,使用interface{}类型并不是最佳实践;然而,有时这是完成某些事情的唯一方法。