Golang update json field with arbitrary json

huangapple go评论73阅读模式
英文:

Golang update json field with arbitrary json

问题

给定一些 JSON 字符串和一个 JSON 路径:

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

jsonPath := "test.foo2"

还有另一个包含任意 JSON 的字符串:

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

我该如何更新原始的 JSON 字符串,以在指定路径处包含任意 JSON?

// 期望的输出:
`{
  "test": {
    "foo1": "bar1",
    "foo2": {
      "a": "apple",
      "b": [1,2]
    }
  }
}`
英文:

Given some json string, and a jsonpath

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

jsonPath := "test.foo2"

and another string containing arbitrary json

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

How can I update the original json string, to contain the arbitrary json at the specified path?

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

答案1

得分: 1

找到了解决方案

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

我最初是直接设置JSON字符串,这只会导致它被解释为字符串

// 这样不起作用:
newJson, err := sjson.Set(MyJson, jsonPath, arbitraryJson)
// 输出
`{
  "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)
// 输出
`{
  "test": {
    "foo1": "bar1",
    "foo2": {
      "a": "apple",
      "b": [1,2]
    }
  }
}`
英文:

Found the solution

Using https://github.com/tidwall/sjson

I was originally setting the json string directly, which just caused it to be interpreted as a string

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

But just unmarshalling the arbitrary json first gives the intended result

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]
    }
  }
}`

huangapple
  • 本文由 发表于 2022年11月22日 23:24:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/74535076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定