首页 > 解决方案 > json_normalize:访问库和数组形式的数据

问题描述

我正在尝试在以下嵌套 json 中提取“资源”的值

{
    "Statement": [
        {
            "Effect": "A-----------",
            "Action": [
                "logs:C-----------",
                "logs:P-----------"
            ],
            "Resource": [
                "a----",
                "b----",
                "c----"
            ]
        }
        {
            "Effect": "A-----------",
            "Action": "l-----------p",
            "Resource": "a-----------*"
        },
        {
            "Effect": "A-----------",
            "Action": [
                "-----------",
                "l-----------"
            ],
            "Resource": [
                "a----",
                "b----"
            ]
        }
    ]
}

如您所见,"Resource":["value"]第一个和第三个示例的“资源”信息位于数组中,但第二个示例为库形式{"Resource": "value"}

在我从中提取信息的实际 json 文件中,大多数“资源”数据都是数组形式。

我可以使用以下代码获取数组的信息:

df = pd.json_normalize(response['Document']['Statement'], record_path=['Resource'])

但由于库形式的“资源”在数组形式的两者之间,它给了我这个错误:

TypeError(TypeError: {'Resource': '----'} has non list value ---- for path Resource. Must be list or null.

我知道我可以使用下面的代码访问图书馆信息,但我想一次性获取所有“资源”实例的信息。

table_df = pd.json_normalize(response['Statement'])
table_df = table_df.reindex(columns=['Resource'])

我可以用什么方法解决这个问题?

标签: pandas

解决方案


您不需要 pandas 来操作 json。

import pandas as pd

data = {
    "Statement": [
        {
            "Effect": "A-----------",
            "Action": [
                "logs:C-----------",
                "logs:P-----------"
            ],
            "Resource": [
                "a----",
                "b----",
                "c----"
            ]
        },
        {
            "Effect": "A-----------",
            "Action": "l-----------p",
            "Resource": "a-----------*"
        },
        {
            "Effect": "A-----------",
            "Action": [
                "-----------",
                "l-----------"
            ],
            "Resource": [
                "a----",
                "b----"
            ]
        }
    ]
}

resource = list()
for statement in data['Statement']:
    if isinstance(statement['Resource'], list):
        resource.extend(statement['Resource'])
    else:
        resource.append(statement['Resource'])
df = pd.Series(resource)

然后你会得到一个看起来像这样的系列:

df
0            a----
1            b----
2            c----
3    a-----------*
4            a----
5            b----
dtype: object

推荐阅读