duan19850312
duan19850312
2018-08-11 01:25
浏览 957

将新的键值对添加到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
    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
    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
    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

    点赞 评论