json - 在嵌套的复杂 JSON 中搜索键
问题描述
我有一个带有树深度嵌套对象和对象列表的 JSON。我想在这样的 JSON 中搜索一个确切的键。
{
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5e37f7907303f206c87eb7d3"),
"$db": "db"
}
"objlist" : [
{
"$ref" : "coll",
"$id" : ObjectId("5ec57e3a72b4e11ac7239748"),
"$db": "db"
}
{
"$ref" : "coll",
"$id" : ObjectId("5e26e09eb0d1301b1931e1aa"),
"$db": "db"
} ],
"nestedobj" : {
"created" : ISODate("2020-05-20T19:00:10.609Z"),
"empty" : {
},
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5ec57e3a72b4e11ac723974b"),
"$db": "db"
}
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5f7206393c7b9885bc80607d"),
"$db": "db"
} },
"obj" : {
"x" : "xxx",
"y" : "yyy",
"z" : "zzz"
},
"nestedobjlist" : [
{
"created" : ISODate("2020-05-14T12:35:14.340Z"),
"updated" : ISODate("2020-05-14T12:35:14.340Z"),
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5e37f7907303f206c87eb7d3"),
"$db": "db"
}
"x" : "xxx",
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5ebd3ae7d5d9e5502a48cb23"),
"$db": "db"
} },
{
"created" : ISODate("2020-05-14T12:35:14.340Z"),
"updated" : ISODate("2020-05-14T12:35:14.340Z"),
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5e37f7907303f206c87eb7d3"),
"$db": "db"
}
"x" : "xxx",
"obj" : {
"$ref" : "coll",
"$id" : ObjectId("5f7206393c7b9885bc80607d"),
"$db": "db"
} }
],
"empty" : {
},
"created" : ISODate("2020-01-21T10:33:50.378Z"),
"x" : "xxx",
"bool" : false,
"int" : 0
...
}
我已经编写了这个有效的递归函数,但是对于大量条目来说复杂性不会变得太大吗?是否有更好的解决方案来遍历 JSON?
func recurs(doc bson.D, key string) {
for _, k := range doc {
switch e := k.Value.(type) {
case primitive.D:
if len(e) > 0 && e[0].Key == key {
fmt.Println(e)
} else {
recurs(e)
}
case primitive.A:
for _, r := range e {
if len(r.(primitive.D)) > 0 && r.(primitive.D)[0].Key == key {
fmt.Println(r)
} else {
recurs(r.(primitive.D))
}
}
}
}
}
我在 MongoDB 数据库中检索数据,然后在 BSON 中操作文档,其中:
type E struct {
Key string
Value interface{}
}
type D []E
type A []D
解决方案
I'm not sure about BSON, but I've used tools like https://github.com/PaesslerAG/jsonpath to pull values out of big JSON docs where I didn't want to create a set of structures. jsonpath works like XPath, where you can parse the JSON into a generic interface{} and then give an expression to pull out the nodes you want.
推荐阅读
- user-interface - UI如何评估?
- iphone - 创建新会话是不可能的,因为“createSession”需要 HttpClient,
- angular - Angular FormGroup valueChanges 将属性转换为数组
- java - 我在 android apk 中执行命令,但我无法获得正确的返回
- windows - 使用 Windows 默认凭据的 UWP NTLM 身份验证
- javascript - 如何在javascript中找到程序的类和函数的行号
- azure-active-directory - 在使用 Directory.AccessAsUser.All 的本机应用程序中是否需要管理员同意?
- javascript - 在angularjs中突出显示从一个列表框移动到另一个列表框的项目
- c# - 合并两个 XDocument
- android - 数据源PagedList Android无效