pandas - 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 来操作 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
推荐阅读
- python - Python:如何通过UDP同时接收来自多个客户端的二进制数据?
- javascript - Vue2 + Airtable - 如何对 v-for 循环进行排序,使其不是随机顺序?
- html - 如何垂直对齐包含在列表元素中的 div?
- bash - 如何存储 CLI 工具中的值以便稍后在同一个 bash 脚本中使用?
- cookies - 设置 Cookie 子域 + 根
- python - 如何根据用户制作自定义过滤器
- vue.js - 过滤对象键:vue中的值
- python - Jupyter 和虚拟环境的最佳实践
- java - 更新父实体时如何更新子实体?
- python - Python:在应用定义的 hasrsine 函数时出现 groupby() 和 apply() 问题