我有非常具体的问题。 这是我和我一起的json文件。
{
"name" : "myname",
"value" : 0,
"level" : [ {
"name" : "myname",
"value" : 1,
"level" : [ {
"name" : "something",
"value" : 2,
"level" : [ {
"name" : "something",
"value" : 3,
"level" : [ {
"name" : "Phy",
"value" : 4,
"something_retrive" : [ {
"mysupername" : "retrive",
"someID" : "blahblah"
}, {
"something_retrive" : [ {
"mysupername" : "retrive",
"someID" : "blahblah"
"randomdata" : [ {
"data1":"val1"
"data1":"val1"
}, {
"name" : "some",
"size" : 3,
"type" : "float",
} ]
} ]
} ]
} ]
} ]
} ]
}
我需要搜索级别内部级别(可以是递归的任何数字),我也需要知道不。其中直到我找到“something_retrive”,并且在那里也可能有不止一个“mysupername”所以我需要在知道没有之后回复其中的一些。可以使用“mysupername”。
我现在正在使用python并使用它们我可以使用此问题的答案加载json并访问数据Parsing json and searching through it
但我不知道如何在JSON文件中执行搜索和brwosing以及如何知道我处于特定级别。
任何帮助或建议或参考都会有所帮助。
(我搜索了2天但没有运气)
答案 0 :(得分:0)
请注意,根据定义,字典是无序的,因此您可能需要将JSON解码器强制为use an ordereddict。但是,一旦获得了数据,就可以很容易地循环并构建数据结构,从而为您提供访问任何给定数据所需的密钥元组。这是一个例子:
mydict = {
"name" : "myname",
"value" : 0,
"level" : [ {
"name" : "myname",
"value" : 1,
"level" : [ {
"name" : "something",
"value" : 2,
"level" : [ {
"name" : "something",
"value" : 3,
"level" : [ {
"name" : "Phy",
"value" : 4,
"something_retrive" : [
{
"mysupername" : "retrive",
"someID" : "blahblah"
}, {
"something_retrive" : [ {
"mysupername" : "retrive",
"someID" : "blahblah",
"randomdata" : [
{
"data1":"val1"
}, {
"name" : "some",
"size" : 3,
"type" : "float",
}
]
} ]
}
]
} ]
} ]
} ]
}]
}
import collections
def findpaths(container):
def recurse(container, prefix):
if isinstance(container, list):
container = enumerate(container)
else:
container = container.items()
for key, value in container:
keys[key].append(prefix)
fullkey = prefix + (key,)
if isinstance(value, (list, dict)):
recurse(value, fullkey)
else:
values[value].append(fullkey)
keys = collections.defaultdict(list)
values = collections.defaultdict(list)
recurse(container, ())
return keys, values
def retrievebypath(container, keys):
for key in keys:
container = container[key]
return container
keys, values = findpaths(mydict)
print("\nBy key:\n")
for key, value in sorted(keys.items(), key=str):
print(key, sorted(value))
print("\nBy value:\n")
for key, value in sorted(values.items(), key=str):
print(key, sorted(value))
print("\nRetrieving container which has second appearance of mysupername\n")
print(retrievebypath(mydict, keys["mysupername"][1]))