如何使用熊猫从嵌套JSON数组中提取值

时间:2019-02-12 18:05:06

标签: python json pandas csv dataframe

我有一个大的JSON文件(400k行)。我正在尝试隔离以下内容:

政策-“说明”

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

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

熊猫的预期产量:https://imgur.com/a/FVcNGsZ

“策略项”之后的所有内容都重复了整个文件中完全相同的内容。我已经尝试了下面的代码来隔离“用户”。似乎不起作用,我正在尝试将所有这些都转储为CSV。

编辑*这是我尝试尝试的解决方案,但无法使其正常工作-Deeply nested JSON response to pandas dataframe

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

with open("Ranger_Policies_20190204_195010.json") as file:
    jsonDF = json.load(file)
    for item in jsonDF['policies'][0]['policyItems'][0]:
        print ('{} - {} - {}'.format(jsonDF['users']))

编辑2:我有一些可以捕获一些USERS的工作代码,但不能捕获所有USERS。 25中只有11。

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

with open("Ranger_Policies_20190204_195010.json") as file:
    jsonDF = json.load(file)
    pNode = Jnormal(jsonDF['policies'][0]['policyItems'], record_path='users')
    print(pNode.head(500))

编辑3:,这是最终的工作副本,但是我仍然没有复制所有的TABLE数据。我设置了一个循环以简单地忽略一切。捕获所有内容,然后在Excel中对其进行排序,是否有人对我无法捕获所有TABLE值有任何想法?

    json_data = json.load(file)
    with open("test.csv", 'w', newline='') as fd:
        wr = csv.writer(fd)
        wr.writerow(('Database name', 'Users', 'Description', 'Table'))
        for policy in json_data['policies']:
            desc = policy['description']
            db_values = policy['resources']['database']['values']
            db_tables = policy['resources']['table']['values']
            for item in policy['policyItems']:
                users = item['users']
                for dbT in db_tables:
                    for user in users:
                        for db in db_values:
                            _ = wr.writerow((db, user, desc, dbT))```

2 个答案:

答案 0 :(得分:2)

熊猫在这里是过大的:csv标准模块就足够了。您只需迭代策略以提取描述和数据库值,接下来访问policyItems以提取用户:

with open("Ranger_Policies_20190204_195010.json") as file:
    jsonDF = json.load(file)
with open("outputfile.csv", newline='') as fd:
    wr = csv.writer(fd)
    _ = wr.writerow(('Database name', 'Users', 'Description'))
    for policy in js['policies']:
        desc = policy['description']
        db_values = policy['resources']['database']['values']
        for item in policy['policyItems']:
            users = item['users']
            for user in users:
                for db in db_values:
                    if db != '*':
                        _ = wr.writerow((db, user, desc))

答案 1 :(得分:1)

这是一种实现方式,假设您的json数据位于名为json_data的变量中

from itertools import product

def make_dfs(data):
    cols = ['db_name', 'user', 'description']

    for item in data.get('policies'):
        description = item.get('description')
        users = item.get('policyItems', [{}])[0].get('users', [None])
        db_name = item.get('resources', {}).get('database', {}).get('values', [None])
        db_name = [name for name in db_name if name != '*']
        prods = product(db_name, users, [description])
        yield pd.DataFrame.from_records(prods, columns=cols)

df = pd.concat(make_dfs(json_data), ignore_index=True)

print(df)

   db_name          user                               description
0    m2_db          hive  Policy for all - database, table, column
1    m2_db  rangerlookup  Policy for all - database, table, column
2    m2_db     ambari-qa  Policy for all - database, table, column
3    m2_db          af34  Policy for all - database, table, column
4    m2_db          g748  Policy for all - database, table, column
5    m2_db          hdfs  Policy for all - database, table, column
6    m2_db          dh10  Policy for all - database, table, column
7    m2_db          gs22  Policy for all - database, table, column
8    m2_db          dh27  Policy for all - database, table, column
9    m2_db          ct52  Policy for all - database, table, column
10   m2_db  livy_pyspark  Policy for all - database, table, column

Python 3.5.1pandas==0.23.4上进行了测试