json - 如何在python中使用pandas从动态JSON对象中获取所有键
问题描述
我从多个 web 服务中得到一个复杂的 JSON 响应。我需要使用 python 获取各个级别的所有键。要使用 JSON_NORMALISE 我需要知道键名。由于我收到多个回复,我无法提供密钥名称。如果我在外层进行规范化,则较低级别的 json 不会转换为字典。它仍然是json格式。
{'Id': 123,
'oldnumber': 1,
'new number': 8,
'version': 1,
'newversion': 1,
'personList':[{
'id':1,
'name': xyz,
'marks':[{'phy':90,
'che':80
}
{'bot':90,
'zoo':80
},
{'phy':60,
'che':80
}
{'bot':20,
'zoo':80
}
]}
],
'anotherList':[{
'id':1,
'data': xyz,
'some':[{'not':90,
'dot':80
}
{'cot':90,
'pot':80
},
{'ans':60,
'dog':80
}
{'cat':20,
'mat':80
}
]}
]
}
如何从我从响应中获得的 JSON 中读取所有键名?
解决方案
要从复杂的 JSON 对象中获取所有键,我们可以使用简单的 python 直接遍历 JSON 对象。我从下面的链接得到了解决方案。
参考 - https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10
我稍微修改了代码,现在我可以从 JSON 中获取所有密钥
def normalise_json(y): out = set()
def normalise(x):
if type(x) is dict:
for a in x:
out.add(a)
normalise(x[a])
elif type(x) is list:
for a in x:
normalise(a)
normalise(y)
return out
推荐阅读
- angularjs - “未能实例化模块 jobApp 由于:错误:[$injector:modulerr]”
- ruby-on-rails - 如何绕过 Rails 服务器对 js 运行时的限制?
- meteor - Meteor Blaze 在表格中显示对象的动态值
- r - 从相关矩阵中过滤 p 值而不丢失行名和列名
- r - 按下操作按钮后清空由 reactiveValues() 创建的数据框
- arrays - 为什么将可分配数组作为自动数组传递给形状错误的子例程时,gfortran 的运行时边界检查不起作用?
- c# - 在视图中显示来自数据库的多个图像
- c - 为什么在 for 循环中使用 fgets 和 sscanf 时出现分段错误?
- c++ - 如何更改整数向量中的重复元素,以便在保持元素数量和单调性的同时不重复任何值?
- git - 如何用较旧的提交替换远程 Git 存储库?