我有一个如下所示的 jsonresult_json = { "status":"Gov info", "user_input":[ { "rule":"Location" }, { "des": "This is for location1", "value": 1 }, { "des": "This is for location2", "value": 2 }, { "rule":"District" }, { "des": "This is for district1", "value": 1 }, { "des": "This is for district2", "value": 2 }, { "des": "This is for district3", "value": 3 }, { "des": "This is for district4", "value": 4 }, { "rule":"Country" }, { "des": "This is for country1", "value": 1 }, { "rule":"Continent" }, { "des": "This is for continent1", "value": 1 }, { "des": "This is for continent2", "value": 2 }, ], "source":"Gov", "id":"5ass1"}我也有这样的清单lookup = [u'Location', u'District', u'Country', u'Continent']现在我想要做的是查看列表的每个值,检查 json 是否具有相同的值(该值是针对rule键存储的)并在它之后立即获取子 json 直到我点击下一个rule. 例如列表查找中的第一个值是Location。现在我遍历user_input键的值,检查子键rule并找出值Location匹配,然后立即存储后续字典,直到我点击下一个键rule。所以对于查找值Location,在检查 json 并收集后续字典后,这就是我将如何存储filtered_output = { "Location":[ { "des":"This is for location1", "value":1 }, { "des":"This is for location2", "value":2 } ]}现在我寻找下一个查找值,即District,将存储的 json 的后续部分是filtered_output = { "Location":[ { "des":"This is for location1", "value":1 }, { "des":"This is for location2", "value":2 } ], "District":[ { "des":"This is for district1", "value":1 },我尝试做类似下面的事情filtered_output = {}for i in lookout: temp_json = [] for j in result_json["user_input"]: if j.get("rule") == i: temp_json.append(j)在这里,它只存储包含键的字典,rule但在遇到下一个rule键之前不会进一步继续。我不知道如何使这项工作。任何帮助将不胜感激。
1 回答
料青山看我应如是
TA贡献1772条经验 获得超8个赞
我会首先将您的输入转换为您想要的格式,然后我将仅过滤键,如下所示:
user_input = result_json["user_input"]
transformed_user_input = {}
for el in user_input:
if "rule" in el:
current_rule = el["rule"]
transformed_user_input[current_rule] = []
else:
transformed_user_input[current_rule].append(el)
lookup = [u'Location', u'District', u'Country', u'Continent']
filtered_user_input = { key: transformed_user_input[key] for key in lookup}
这样,您只处理一次输入(不知道它有多大)。
添加回答
举报
0/150
提交
取消