簡體   English   中英

Golang 用任意 json 更新 json 字段

[英]Golang update json field with arbitrary json

給定一些 json 字符串和一個 jsonpath

myJson := `{
  "test": {
    "foo1": "bar1",
    "foo2": "bar2"
  }
}`

jsonPath := "test.foo2"

和另一個包含任意 json 的字符串

arbitraryJson := `{
  "a": "apple",
  "b": [1,2]
}`

如何更新原始 json 字符串,以在指定路徑包含任意 json?

// expected output:
`{
  "test": {
    "foo1": "bar1",
    "foo2": {
      "a": "apple",
      "b": [1,2]
    }
  }
}`

找到解決方案

使用https://github.com/tidwall/sjson

我本來是直接設置 json 字符串,導致它被解釋為字符串

// This doesn't work:
newJson, err := sjson.Set(MyJson, jsonPath, arbitraryJson)
// output
`{
  "test": {
    "foo1": "bar1",
    "foo2": "{\"a\": \"apple\",\"b\": [1,2]}"
  }
}`

但是首先解組任意 json 會給出預期的結果

var unmarshalled any
_ = json.Unmarshal([]byte(arbitraryJson), &unmarshalled)
newJson, err := sjson.Set(MyJson, jsonPath, unmarshalled)
// output
`{
  "test": {
    "foo1": "bar1",
    "foo2": {
      "a": "apple",
      "b": [1,2]
    }
  }
}`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM