【发布时间】:2017-03-28 02:19:13
【问题描述】:
我很好奇如何使用 pandas 读取以下结构的嵌套 json:
{
"number": "",
"date": "01.10.2016",
"name": "R 3932",
"locations": [
{
"depTimeDiffMin": "0",
"name": "Spital am Pyhrn Bahnhof",
"arrTime": "",
"depTime": "06:32",
"platform": "2",
"stationIdx": "0",
"arrTimeDiffMin": "",
"track": "R 3932"
},
{
"depTimeDiffMin": "0",
"name": "Windischgarsten Bahnhof",
"arrTime": "06:37",
"depTime": "06:40",
"platform": "2",
"stationIdx": "1",
"arrTimeDiffMin": "1",
"track": ""
},
{
"depTimeDiffMin": "",
"name": "Linz/Donau Hbf",
"arrTime": "08:24",
"depTime": "",
"platform": "1A-B",
"stationIdx": "22",
"arrTimeDiffMin": "1",
"track": ""
}
]
}
这里将数组保存为 json。我宁愿把它展开成列。
pd.read_json("/myJson.json", orient='records')
编辑
感谢您的第一个答案。 我应该完善我的问题: 数组中嵌套属性的展平不是强制性的。 只需 [A, B, C] 连接 df.locations['name'] 就可以了。
我的文件包含多个 JSON 对象(每行 1 个)我想保留数字、日期、名称和位置列。但是,我需要加入这些位置。
allLocations = ""
isFirst = True
for location in result.locations:
if isFirst:
isFirst = False
allLocations = location['name']
else:
allLocations += "; " + location['name']
allLocations
我这里的方法似乎效率不高/熊猫风格。
【问题讨论】:
-
最简单的方法,你可以查看我的回答here
标签: python json parsing pandas