展平嵌套列表

时间:2018-11-27 17:36:45

标签: python json python-2.7

不确定是在正确的位置提出问题还是在正确理解这一点。我需要更改字典,以便将出现字段添加到可用性密钥上。例如:“ Availability.Occurrence”:“每日”

 BEFORE
 test_data =  {
              "testDate": "2018-11-19 21:00:00", 
              "testMessage": "This is a test message", 
              "testStatus": "Warning", 
              "Results": [
                         {
                          "Availability": {
                                           "Occurence": "Daily"
                                          }, 
                          "OldestRefreshDate": "2018-11-15 15:40:57 EST", 
                          "TableName": "test"
                         }
                         ], 
              "TaskId": "CheckSourceRefreshDates"
             }
AFTER
     test_data =  {
              "testDate": "2018-11-19 21:00:00", 
              "testMessage": "This is a test message", 
              "testStatus": "Warning", 
              "Results": [
                         {
                          "Availability.Occurrence": "Daily", 
                          "OldestRefreshDate": "2018-11-15 15:40:57 EST", 
                          "TableName": "test"
                         }
                         ], 
              "TaskId": "CheckSourceRefreshDates"
             }

我是Python的新手,只是想弄清楚所有这些。任何帮助表示赞赏。 这是我尝试使用的函数,但是它只会使整个字典变平。

def flatten_json(y):
out = {}

def flatten(x, name=''):
    if type(x) is dict:
        for a in x:
            flatten(x[a], name + a + '.')
    elif type(x) is list:
        i = 0
        for a in x:
            flatten(a, name + '.')
            i += 1
    else:
        out[name[:-1]] = x

flatten(y)

return out

0 个答案:

没有答案