python - 将带有列表和 dics 的 JSON 转换为数据框
问题描述
我想将 JSON 文件转换为易于搜索和定位有用信息的数据框。JSON 如下所示:
[
{
"testId": "test1",
"testType": [
{
"value": "a",
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"candidate": [
{
"value": {
"id": "b",
"name": "test"
},
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"testsite": [
{
"value": "c",
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
]
},
{
"testId": "test2",
"testType": [
{
"value": "SG",
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"maxcandidates": [
{
"value": {
"amount": "75"
},
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"candidate": [
{
"value": {
"id": "sei",
"name": "long island Limited"
},
"startDate": "2019-01-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"mincandidates": [
{
"value": {
"amount": "5"
},
"startDate": "2018-04-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
],
"testSite": [
{
"value": "5227",
"startDate": "2018-04-01T08:00:00",
"endDate": "2029-01-01T08:00:00"
}
]
}
]
它是 json 文件的一部分。这个 JSON 文件包含列表,一些属性包含字典。1 标准化这些数据的最有效方法是什么?2 如果我想在整个 JSON 文件中将“testType”转换为带有“testId”元数据的数据框,我该怎么做?
我将此命令用作
import json
import pandas as pd
from pandas.io.json import json_normalize
with open('test.json') as f:
d=json.load(f)
type=json_normalize(data=d[:]['testType'],
meta=['testId'])
它出现了 TypeError: list indices must be integers or slices, not str
或者如果我使用
import json
import pandas as pd
from pandas.io.json import json_normalize
with open('test.json') as f:
d=json.load(f)
type=json_normalize(data=d[0]['testType'],
meta=['testId'])
我可以将它转换为数据框,但它只能给我数组中的第一个元素而不是所有东西。
解决方案
您可能可以执行以下操作:
pd.concat([json_normalize(data=e['testType'], meta=['testId']) for e in d])
value startDate endDate
0 a 2019-01-01T08:00:00 2029-01-01T08:00:00
0 SG 2019-01-01T08:00:00 2029-01-01T08:00:00
推荐阅读
- neovim - Vim `:find` 可以访问 `.gitignore` 的东西
- delphi - 如何检查一个类的实例是否存在
- serialization - Symfony 5 将 json 嵌套对象反序列化为 DTO
- html - HTML和CSS元素问题显示参数
- css - 根据背景在特定颜色之间改变文本
- c++ - /// 在 C++ 中是什么意思?
- php - 使用 PHP 列出目录中的所有文件夹和子文件夹
- mysql - 在将数据从一个表插入到另一个表时,我们可以编写除列名之外的查询吗?
- r - 使用 BDportfolio_optim 函数(PortfolioOptim 包)最小化 CVaR
- python-3.x - 如何使用 python 请求处理 InvalidChunkLength 错误?