duan19850312 2018-08-11 01:25
浏览 1532
已采纳

将新的键值对添加到JSON对象

I am connecting to an API which gives a rather large json payload. I need to add a key and value to the root object.Once I do ioutil.Readall from the package "net/http" the JSON is a byte array.

My goal is to just simply add to the structure and move on. As an example, the following the pretty similar to what I am doing: https://tutorialedge.net/golang/consuming-restful-api-with-go/

So how can I simply add to a JSON structure another element (key: value)?

  • 写回答

3条回答 默认 最新

  • dongxie3681 2018-08-11 18:15
    关注

    If all you want to do is add a key and value to the root object and produce new JSON, and you don't care about having the data in a structure, you can unmarshal into map[string]interface{}, add your value, and then marshal again:

    var m map[string]interface{}
    err := json.Unmarshal(data, &m)
    m["new_key"] = newValue
    newData, err := json.Marshal(m)
    

    (I'm not checking for errors, but you should do that of course.) Take a look at https://golang.org/pkg/encoding/json/ for more information about how to deal with JSON in Go.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dongsui4658 2018-08-11 03:33
    关注

    Since you have a byte data, you need to parse it and store the result in a variable that has your json structure using json.Marshal.

    Then after, to add a new key value pair, you can define a new struct with the key and its data type

    var variable type1
    // Unmarshal the byte data in a variable
    json.Unmarshall(data, &variable)
    // to add a new key value you can define a new type
    type type2 struct {
    type1
    key type
    }
    // and you can add
    variable2 := type2{variable, newValueToAdd}
    
    评论
  • dtu1747 2018-08-13 14:27
    关注

    While deserializing & reserializing is the more "correct" approach, it may be overkill for just adding a value at the root, which can be done with simple string manipulation (really byte slice manipulation, but the semantics are similar and it's arguably easier):

    data := []byte(`{"foo": 1, "bar": true}`)
    ins := []byte(`, "baz": "hello"`)    // Note the leading comma.
    closingBraceIdx := bytes.LastIndexByte(data, '}')
    data = append(data[:closingBraceIdx], ins...)
    data = append(data, '}')
    

    This is more error-prone, because it is unaware of JSON syntax entirely, but it's safe enough for most cases and for large JSON documents it is more efficient than a parse, insert, and reserialize.

    Playground example: https://play.golang.org/p/h8kL4Zzp7rq

    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥60 PCDN如何使用宽带的电视业务通道拨号叠加带宽?
  • ¥15 遇到这种校园宽带网络应该怎么样解决?
  • ¥30 AXI VIP验证多余打印问题
  • ¥15 利用加权最小二乘法求某品牌手机价格指标,已按照总销量计算出权重,各类型号手机价格已知,如何求得价格指标?
  • ¥15 如何自制一个硬件钱包,有兴趣的朋友一起交流
  • ¥15 (关键词-聊天软件)
  • ¥15 求大家看看这个编程的编法没有思路啊
  • ¥20 WSL打开图形化程序子窗口无法点击
  • ¥15 Jupyter Notebook 数学公式不渲染
  • ¥20 ERR_CACHE_MISS 确认重新提交表单