我想创建一个可以转换为json对象的映射,例如

{
   "a": "apple",
   "b": 2
}

but golang specifies that the map be declare with types, so I can have map[string]string or map[string]int. How do I create a json object like the above?

Note: I won't know what data and/or types I need until runtime or when I need to create the json object. Therefore I can't just create an object like

type Foo struct {
    A string `json:"a"`
    B int `json:"b"`
}

推荐答案

您可以始终使用interface{}来存储任何类型.正如encoding/json包中的文档所说:

为了将JSON解组为接口值,Unmarshal将JSON解组为包含在接口值中的具体值.如果接口值为nil,即其中没有存储具体值,则Unmarshal会在接口值中存储以下内容之一:

bool, for JSON booleans
float64, for JSON numbers
string, for JSON strings
[]interface{}, for JSON arrays
map[string]interface{}, for JSON objects
nil for JSON null

只需执行以下操作:

m := map[string]interface{}{"a":"apple", "b":2}

Json相关问答推荐

如何在Haskell中解析JSON,其中字段的名称可以是多个值之一,但应该转换为单个Haskell类型?

具有 (RegEx) 模式的 json-schema 中的枚举

try 使用 JQ 转换 JSON 中过于复杂的对象数组

父键中的 Perl JSON 数组

通过 xslt 将内部 json 转换为 xml 时遇到问题

从字节解码 JSON 数据,将 float 值更改为 int

MarkLogic REST 资源 API - 仅使用一个 POST 请求修补多个文档

在 rust 中从 API 反序列化 serde_json

序列化特定类型时如何使 JSON.Net 序列化程序调用 ToString()?

JSON RPC - 什么是id?

将 JSON 对象推送到 localStorage 中的数组

是否可以将数据写入本地 json 文件,除了Angular 之外什么都没有?

如何按键查找特定的 JSON 值?

有没有办法在 angular.json 中扩展配置?

Spring restTemplate 获取原始 json 字符串

严重:找不到媒体类型 = 应用程序/json、类型 = 类 com.jersey.jaxb.Todo、通用类型 = 类 com.jersey.jaxb.Todo 的 MessageBodyWriter

JSON 模式 - 如果对象*不*包含特定属性则有效

Protocol Buffer vs Json - 何时 Select 一个而不是另一个

python追加到json对象中的数组

处理 HTTP 请求正文中的可选 JSON 字段