python - python在初始部分读取带有标题的json字符串
问题描述
我正在尝试从包中获取输出(在包文档中定义为“jsonDICT”)并最终将其写为 csv。我将调用此 PackResult,它是一个字典。
print(PackResult) 的第一个也是最后几个字符如下所示:
{'startDate': '2019-11-01T00:00:00', 'endDate': '2020-03-31T00:00:00', 'timezone': 'UTC', 'groupBy': 'DAILY', 'numberOfDocuments': 34486, 'volume':
[{'startDate': '2019-11-01T00:00:00', 'endDate': '2019-11-02T00:00:00', 'numberOfDocuments': 0},
{'startDate': '2019-11-02T00:00:00', 'endDate': '2019-11-03T00:00:00', 'numberOfDocuments': 1},
{'startDate': '2019-11-03T00:00:00', 'endDate': '2019-11-04T00:00:00', 'numberOfDocuments': 0}
...
{'startDate': '2020-03-30T00:00:00', 'endDate': '2020-03-31T00:00:00', 'numberOfDocuments': 1389}], 'status': 'success'}
所以字符串的第一部分包含“样本”列标题,然后一旦遇到左括号,就会显示实际值及其各自的列标题。
我正在尝试使用 pandas 来完成繁重的工作,但我似乎无法让它读取第一组标题,然后读取数据。本质上,
import pandas as pand
import json
df = pand.read_json(json.dumps(PackResult),'records','series')
print(df)
给了我这个:
startDate 2019-11-01T00:00:00
endDate 2020-03-31T00:00:00
timezone UTC
groupBy DAILY
numberOfDocuments 34486
volume [{'startDate': '2019-11-01T00:00:00', 'endDate...
status success
和
df = pand.read_json(json.dumps(PackResult),'records','frame')
给我:
startDate endDate timezone groupBy numberOfDocuments volume status
0 2019-11-01T00:00:00 2020-03-31T00:00:00 UTC DAILY 34486 {'startDate': '2019-11-01T00:00:00', 'endDate'... success
1 2019-11-01T00:00:00 2020-03-31T00:00:00 UTC DAILY 34486 {'startDate': '2019-11-02T00:00:00', 'endDate'... success
2 2019-11-01T00:00:00 2020-03-31T00:00:00 UTC DAILY 34486 {'startDate': '2019-11-03T00:00:00', 'endDate'... success
3 2019-11-01T00:00:00 2020-03-31T00:00:00 UTC DAILY 34486 {'startDate': '2019-11-04T00:00:00', 'endDate'... success
4 2019-11-01T00:00:00 2020-03-31T00:00:00 UTC DAILY 34486 {'startDate': '2019-11-05T00:00:00', 'endDate'... success
我错过了什么?
提前致谢
解决方案
啊。新的一天和一些休息让我明白了我所缺少的东西:
df = pand.read_json(json.dumps(PackResult["volume"]),'records','frame')
这导致
# startDate endDate numberOfDocuments
0 2019-11-01T00:00:00 2019-11-02T00:00:00 0
1 2019-11-02T00:00:00 2019-11-03T00:00:00 1
2 2019-11-03T00:00:00 2019-11-04T00:00:00 0
3 2019-11-04T00:00:00 2019-11-05T00:00:00 0
4 2019-11-05T00:00:00 2019-11-06T00:00:00 0
推荐阅读
- python - 如何用 numpy 计算表格的第 95 个百分位数?
- excel - VBA 宏可在不同工作表中创建不同范围的单个 pdf
- sql - 使用 VBA for Excel:从 ODBC SQL 中提取数据,如何使用“今天前一年”的值?
- c# - 在 VS2017/2019 中构建 StackOverflowException
- javascript - 将 Vue.JS 项目转换为 Nuxt.JS 项目
- mysql - 永久阻止 mariadb
- .net - 允许从 v4.8 降级到 v4.5.1
- javascript - 元素在 Chrome 77 上短暂消失并重新出现
- r - 自动将工作目录设置为 R 中当前打开的文件夹
- java - 如何在 EditText 中进行正常的行编号?