如何根据Python中的特定条件将json的特定部分存储在变量中?

时间:2019-04-10 12:16:24

标签: python json dictionary

我有一个看起来像下面的json

result_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匹配,然后立即存储后续字典,直到我按下下一个键{{ 1}}。因此,对于查找值rule,在检查json并收集后续字典后,这就是我的存储方式

Location

现在,我寻找下一个查找值filtered_output = { "Location":[ { "des":"This is for location1", "value":1 }, { "des":"This is for location2", "value":2 } ] } ,将要存储的json的后续部分是

District

我尝试做下面的事情

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
      },
      {  
         "des":"This is for district2",
         "value":2
      },
      {  
         "des":"This is for district3",
         "value":3
      },
      {  
         "des":"This is for district4",
         "value":4
      }
   ]
}

此处仅存储包含键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键之前不会继续。我不确定如何进行这项工作。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

我首先将输入内容转换为所需的格式,然后我将对这些键进行过滤,如下所示:

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}

这样,您只处理一次输入(不知道输入有多大)。