首页 > 解决方案 > 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  

我错过了什么?

提前致谢

标签: pythonpandas

解决方案


啊。新的一天和一些休息让我明白了我所缺少的东西:

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  

推荐阅读