Pandas read_json 脚本曾经正常运行,现在出现错误。

huangapple go评论67阅读模式
英文:

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 = &quot;https://SomeURL/SomeEndpoint&quot;
print(&#39;URL set&#39;)

# Connect to endpoint with credentials and put results in dictionary
URLresponse = requests.get(url,auth=(&quot;SomeUser&quot;, &quot;SomePassword&quot;), verify=True)
print(&#39;connection to endpoint&#39;)

# Load the response as proper JSON into a var
rawdata = (URLresponse.content)
print(type(rawdata))
print(&#39;populating variable&#39;)

# print(rawdata)

# Load the var into a dataframe
df = pd.read_json(rawdata) 
print(&#39;load variable into df&#39;)

print(df)

This used to work fine but now it is producing an error as following:

  File &quot;C:\Program Files\Python310\lib\site-packages\pandas\io\common.py&quot;, line 901, in get_handle
    raise TypeError(
TypeError: Expected file path name or file-like object, got &lt;class &#39;bytes&#39;&gt; 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(&#39;utf-8&#39;)))

You will need to include import io earlier in your file as well.

huangapple
  • 本文由 发表于 2023年6月16日 07:25:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76486080.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定