Python是否可以将JSON 文本写入Excel文件?
通常,我会将JSON响应加载到Pandas数据框中,然后将其写入Excel:
import pandas
form pandas.io.json import json_normalize
import requests
def df_to_excel(df, filename):
writer = pandas.ExcelWriter(filename)
df.to_excel(writer, 'Sheet1')
writer.save()
response = requests.get(url, params).json()
df = json_normalize(response)
df_to_excel(df, 'Response.xlsx')
但这需要将JSON文本转换为Python对象,从而将"
替换为'
,false
替换为False
,null
替换为None
等等,我不想要。
答案 0 :(得分:1)
您可以先将json转换为字典,然后按照此处Write dictionary values in an excel file的建议转换为excel文件:
import os
import sys
import time
import serial
import serial.tools.list_ports
print('Search...')
ports = serial.tools.list_ports.comports(include_links=False)
for port in ports :
print('Find port '+ port.device)
ser = serial.Serial(port.device)
if ser.isOpen():
ser.close()
ser = serial.Serial(port.device, 9600, timeout=1)
ser.flushInput()
ser.flushOutput()
print('Connect ' + ser.name)
密钥正在使用import json
import xlsxwriter
import requests
response = requests.get(url, params)
d = json.loads(response.text)
workbook = xlsxwriter.Workbook('data.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0
for key in d.keys():
row += 1
worksheet.write(row, col, json.dumps(key))
for item in d[key]:
worksheet.write(row, col + 1, json.dumps(item))
row += 1
workbook.close()
来将pythonic格式转换回json格式。例如,json.dumps()
返回json.dumps(None)