嵌套Json,使用Python递归优化吗?

时间:2019-02-13 13:17:32

标签: python json pandas csv dataframe

非常感谢How to extract values from nested JSON array using pandas的帮助者。

我的老板对结果感到满意,并且我能够略微优化代码以获取更多细节:

政策-“说明”和“组”

策略项-“用户”和“数据库值”

JSON文件-https://pastebin.com/hv8mLfgx

import pandas as pd
from pandas.io.json import json_normalize as Jnormal
import json
import pprint, csv

with open(r"C:\\Users\Jaz\Documents\Python\JSON Parse\Modded2.json") as file:
    json_data = json.load(file)
    with open("RangerFinal.csv", 'w', newline='') as fd:

        wr = csv.writer(fd)
        wr.writerow(('Database name', 'Users', 'Description', 'Table', 'Users'))
        for policy in json_data['policies']:
            desc = policy['description']
            db_values = policy['resources']['database']['values']
            db_tables = policy['resources']['table']['values']
           # db_Groups = policy['policyItems']['groups']

            for item in policy['policyItems']:
                users = item['groups']
                for user in users:
                    for db in db_values:
                        for dbT in db_tables:
                            #for usrGrp in db_Groups:
                             use = item['users']
                             for ppl in use:
                                 _ = wr.writerow((db, user, desc, dbT, ppl)) 
                        #elif db == " ":

熊猫的预期产量:

Expected Output

一个朋友提到使用递归和映射来避免NestedLoops。我是Python的初学者,因此我研究了递归,但不太了解。有人愿意帮助我了解如何使用递归遍历JSON树吗?

我真的需要一直摆脱对嵌套FOR和IF循环的依赖。

谢谢

0 个答案:

没有答案