英文:
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]
}
}
}`
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论