【发布时间】:2022-08-14 05:27:03
【问题描述】:
我试图了解如何将包含 JSON 的 URL 转换为数据框。我正在测试这个示例代码:
import requests
r = requests.get(\'https://www.chsli.org/sites/default/files/transparency/111888924_GoodSamaritanHospitalMedicalCenter_standardcharges.json\')
print(r.json())
这给了我这个:
{\"name\":\"Good Samaritan Hospital Medical Center\",\"tax_id\":\"11-1888924\",\"code\":\"57320\",\"code type\":\"cpt\",\"code description\":\"Closure of abnormal drainage tract from bladder into vagina\",\"payer\":\"humana - medicare advantage\",\"patient_class\":\"O\",\"gross charge\":\"23452.80\",\"de-identified minimum negotiated charge\":\"769.90\",\"payer-specific negotiated charge\":\"3154.88\",\"de-identified maximum negotiated charge\":\"3154.88\",\"discounted cash price\":\"4690.56\"}
{\"name\":\"Good Samaritan Hospital Medical Center\",\"tax_id\":\"11-1888924\",\"code\":\"57320\",\"code type\":\"cpt\",\"code description\":\"Closure of abnormal drainage tract from bladder into vagina\",\"payer\":\"HEALTH FIRST\",\"patient_class\":\"O\",\"gross charge\":\"23452.80\",\"de-identified minimum negotiated charge\":\"769.90\",\"payer-specific negotiated charge\":\"769.90\",\"de-identified maximum negotiated charge\":\"3154.88\",\"discounted cash price\":\"4690.56\"}
: 421
现在,如果我尝试将所有内容都放入数据框中,就像这样......
df = pd.read_json(r.json(), orient=\'index\')
print(df.head())
我收到此错误:
NameError: name \'df\' is not defined
我认为可能有一种定制的方式来做到这一点,但我不确定。如何将此 JSON 转换为数据框?根据 JSON 结构的不同场景,是否有不同的方法来做到这一点?
-
您编写的代码不会发生这种情况。你刚才在行上分配了
df,它不能是未定义的。该错误消息与转换 JSON 无关,它是一个变量范围问题。 -
我认为最后是 \': 421\' 。我认为这就是它被抛弃的原因。我不太了解 JSON,无法确定这里发生了什么。
-
该 URL 不包含有效的 JSON。它是多个 JSON 对象,每个都在单独的行上,但它应该是 JSON 对象的数组。
-
但是,如果读取 JSON 时出现问题,您应该会从
pd.read_json()收到错误,而不是它后面的行。您是否在函数中读取 JSON,然后尝试在调用者中打印它?如果你在函数中没有global df,你会得到这个错误。
标签: python json python-3.x dataframe