dongliang1996
2019-09-13 23:48
浏览 848

如何在JSON序列化中添加方括号?

I am trying to send a post request to a API endpoint. The endpoint does not work without brackets in the JSON data.

map1: = map[string] map[string] interface {} {}
map2: = map[string] interface {} {}
map2["firstObject"] = "value1"
map2["secondObject"] = "value2"

map1["jsonName"] = map2
b, err: = json.Marshal(map1)
if err != nil {
    panic(err)
}

fmt.Println(string(b)) // outputs: {"jsonName":{"firstObject":"value1","secondObject":"value2"}}

I need the output to be: {"jsonName":[{"firstObject":"value1","secondObject":"value2"}]}

However, I am getting this: {"jsonName":{"firstObject":"value1","secondObject":"value2"}}

图片转代码服务由CSDN问答提供 功能建议

我正在尝试向API端点发送发布请求。 没有JSON数据中的方括号,端点无法正常工作。

  map1:= map [string] map [string]接口{} {} 
map2:= map [string]接口{  } {} 
map2 [“ firstObject”] =“ value1” 
map2 [“ secondObject”] =“ value2” 
 
map1 [“ jsonName”] = map2 
b,错误:= json.Marshal(map1)
if  err!= nil {
 panic(err)
} 
 
fmt.Println(string(b))//输出:{“ jsonName”:{“ firstObject”:“ value1”,“ secondObject”:“ value2  “}} 
   
 
 

我需要输出为: {” jsonName“:[{” firstObject“:” value1“,” secondObject“:” value2“}]}

不过,我得到的是: {” jsonName“:{” firstObject“:” value1“,” secondObject“:” value2 “}}

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongye1912 2019-09-14 00:06
    已采纳

    Your indicated payload is passing a map as the value of jsonName, when the API needs an array of maps.

    It may help if you create the inner map first:

    map2 := map[string]interface{}{
        "firstObject":  "value1",
        "secondObject": "value2",
    }
    

    Then create your outer map as a map of string => []interface{}, giving your key and value:

    map1 := map[string][]interface{}{
        "jsonName": []interface{}{map2},
    }
    

    You can do it all in one shot as:

    map1 := map[string][]interface{}{
        "jsonName": []interface{}{
            map[string]interface{}{
                "firstObject":  "value1",
                "secondObject": "value2",
            },
        },
    }
    
    点赞 打赏 评论

相关推荐 更多相似问题