问题描述
我遇到了一个奇怪的 JSON 响应,需要将它保存到 excel,我尝试过 Pandas,但它没有以预期的方式工作(或者我使用它不正确,我是 Python 新手),现在我我正在尝试使用 xlwt
对其进行格式化,但我在 params
响应中得到的唯一 JSON
是“高度、左侧、顶部、宽度”:
例如:
{'rect': {'angle': -90,'height': 12,'left': 31,'top': 22,'width': 12},'word': 'A'},{'rect': {'angle': -90,'left': 301,'top': 23,'width': 14},'word': 'B'},'height': 11,'left': 698,'top': 25,'width': 11},'word': 'D'},'height': 10,'left': 829,'word': 'E'},'left': 909,'word': 'F'},'left': 993,'top': 24,'width': 13},'word': 'G'},'left': 1076,'word': 'H'}
......以及更多行
我不能只是遍历它,因为如果我这样做,它不会开始一个新行。
请告诉我如何使用“高度、左侧、顶部、宽度”。
解决方法
这是一个普通的json响应,但它是一个嵌套响应,这使得直接加载到pandas中很困难。在下面的解决方案中,我假设您将 loaded the json response 作为名为“data”的字典的 Python 列表。
import pandas as pd
data = [{'rect': {'angle': -90,'height': 12,'left': 31,'top': 22,'width': 12},'word': 'A'},{'rect': {'angle': -90,'left': 301,'top': 23,'width': 14},'word': 'B'},'height': 11,'left': 698,'top': 25,'width': 11},'word': 'D'},'height': 10,'left': 829,'word': 'E'},'left': 909,'word': 'F'},'left': 993,'top': 24,'width': 13},'word': 'G'},'left': 1076,'word': 'H'}]
#assuming you wish to include the word variable in a column as well,let's add it to the 'rect' key so we can load the rect keys into a pandas dataframe
for i in data:
i['rect']['word'] = i['word']
#we need to create a list that only contains the data from the rect keys,otherwise pandas can't load it. So let's use list comprehension
df=pd.DataFrame([i['rect'] for i in data])
df.to_excel('output.xlsx')
输出:
angle height left top width word
0 -90 12 31 22 12 A
1 -90 12 301 23 14 B
2 -90 11 698 25 11 D
3 -90 10 829 25 12 E
4 -90 11 909 23 14 F