英文:
Pandas read_json script that used to work now produces an error
问题
我有一个脚本,最近一直运行良好,但现在出现错误。
import requests
import pandas as pd
# 将URL设置为给定的端点
url = "https://SomeURL/SomeEndpoint"
print('已设置URL')
# 使用凭据连接到端点并将结果放入字典中
URLresponse = requests.get(url, auth=("SomeUser", "SomePassword"), verify=True)
print('连接到端点')
# 将响应加载为正确的JSON格式变量
rawdata = (URLresponse.content)
print(type(rawdata))
print('填充变量')
# 打印原始数据
# print(rawdata)
# 将变量加载到数据框中
df = pd.read_json(rawdata)
print('将变量加载到数据框中')
print(df)
这以前正常工作,但现在出现以下错误:
File "C:\Program Files\Python310\lib\site-packages\pandas\io\common.py", line 901, in get_handle
raise TypeError(
TypeError: 期望文件路径名或类似文件的对象,但得到了<class 'bytes'>类型
我该如何继续排除此问题?
英文:
I have a script that up until recently worked fine, but is now producing an error.
import requests
import pandas as pd
# Set the url to given endpoint
url = "https://SomeURL/SomeEndpoint"
print('URL set')
# Connect to endpoint with credentials and put results in dictionary
URLresponse = requests.get(url,auth=("SomeUser", "SomePassword"), verify=True)
print('connection to endpoint')
# Load the response as proper JSON into a var
rawdata = (URLresponse.content)
print(type(rawdata))
print('populating variable')
# print(rawdata)
# Load the var into a dataframe
df = pd.read_json(rawdata)
print('load variable into df')
print(df)
This used to work fine but now it is producing an error as following:
File "C:\Program Files\Python310\lib\site-packages\pandas\io\common.py", line 901, in get_handle
raise TypeError(
TypeError: Expected file path name or file-like object, got <class 'bytes'> type
How can I go ahead to troubleshoot this?
答案1
得分: 2
你可以将df = pd.read_json(rawdata)
修改为df = pd.read_json(io.StringIO(rawdata.decode('utf-8')))
你还需要在你的文件中提前包含import io
。
英文:
You can change df = pd.read_json(rawdata)
to df = pd.read_json(io.StringIO(rawdata.decode('utf-8')))
You will need to include import io
earlier in your file as well.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论