在python中将多级JSON解析为Excel

时间:2017-04-11 16:56:07

标签: python json excel

我尝试使用xlwt将多级JSON解析为Excel。 JSON格式是这样的:

{
     "A": {
              "A1": 0, "A2": 0
          },
     "B": {
              "B1": 0, "B2": 0
          }
}

我尝试过关注(显然是在打开并将JSON加载到Python字典中之后):

for k in data:
    for l in data.keys():
        for j in l.keys():
            o = []
            o = j
            ws.write(0, l.keys().index(j)+1, l[j])
        ws.write(data.keys().index(k)+1, l.keys().index(o)+1, o)
    ws.write(data.keys().index(k)+1, 0, k[l])

但我收到" unicode"对象没有属性"键"

2 个答案:

答案 0 :(得分:1)

您可以使用包StyleFrame

首先将数据转换为可在StyleFrame对象中使用的格式,然后只使用StyleFrame对象。

from StyleFrame import StyleFrame

data = {'A': {'A1': 0, 'A2': 0}, 'B': {'B1': 0, 'B2': 0}}
formated_data = {col: [data[col][row] for row in sorted(data[col])] for col in data}

StyleFrame(data).to_excel('output.xlsx',
                          row_to_add_filters=0,
                          columns_and_rows_to_freeze='A2').save()

答案 1 :(得分:0)

我刚做了一点测试。请参阅下面的测试用例,重点介绍如何循环多级字典。我无法确切地说出你所写作的逻辑,所以我会给出一个广义的答案:

In [44]: data
Out[44]: {'A': {'A1': 0, 'A2': 0}, 'B': {'B1': 0, 'B2': 0}}

In [45]: for i in data:
    ...:     print(data[i])
    ...:     
{'A1': 0, 'A2': 0}
{'B1': 0, 'B2': 0}

#You can see that `i` represents  the key, so you access the value paired with that key by doing `data[i]`. In this case, that value is another dictionary.

In [46]: for i in data:
    ...:     for j in data[i]:
    ...:         print(data[i][j])
    ...:         
0
0
0
0

#This is far less illustrative than my contrived example, but `j` represents the key in the dictionary `data[i]`. So this second loop goes through and prints each value of the nested dictionaries. 

如果不清楚,请告诉我。