JSONDecodeError: Expecting value: line 1 column 1 (char 0), when request data!代码工作了一段时间然后它打破了

问题描述

我正在尝试向人口普查局请求地理编码数据。到目前为止,代码运行并获得了超过 1450 条记录(我的总数约为 60K 条记录),但随后它中断并返回此错误

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我的数据如下所示: enter image description here

这是我的功能

def get_fips(df):  
    
    num=len(ven_lst)
    for i,e in df.itertuples(index=False):
        if e not in repostory_lst:
            try:
                num+=1
                address=i
                vendor=e
                link="https://geocoding.geo.census.gov/geocoder/geographies/onelineaddress?address={0}&benchmark=Public_AR_Census2020&vintage=Census2020_Census2020&layers=10&format=json".format(address)
                reponse = requests.get(link).text
                reponse_1=json.loads(response)
                x=reponse_1['result']['addressMatches'][0]['geographies']['Census Blocks'][0]['GEOID'][:11]

                fields=[num,e,x]
                with open(r'fibs&ven.csv','a',newline='') as f: #because my data is big a save all the #data into this csv incase the code breaks
                    writer = csv.writer(f)
                    writer.writerow(fields)
            except (RuntimeError,TypeError,NameError,IndexError):
                pass
        elif e in repostory_lst:
            pass
    #df_result=pd.DataFrame(columns=['vendor Code','fips'],index=range(len(fips_lst)))
    #df_result['vendor Code']=ven_lst
    #df_result['fips']=fips_lst
    #x.to_csv('fibs&ven.csv',mode='a',header=False)
    return None

解决方法

通常情况下,如果服务器端的 API 编写得很好并且您指定了 format=JSON,那么它应该严格只返回 JSON 数据。 但是为了安全起见,您应该在获取 json 响应中添加一个标头。

你也可以用 text 代替 json() 而你不需要用 json.loads

请求喜欢

 headers = {'Accept': 'application/json'}
 reponse_1 = requests.get(link,headers=headers).json()
 # reponse_1=json.loads(response)
,

事实证明,问题是一些地址是邮政信箱,一旦我删除了它们,代码就会按预期工作,

,

当我有一个 handleClick = async () => { const res = await fetch(`${process.env.BACKEND_API_URL}/create-checkout-session`,{ method: 'POST',headers: { "Content-Type": 'application/json' } }) const body = await res.json() window.location.href = body.url } 时,我遇到了这个错误。 我的错误是 500

我将其更改为 DecimalField,结果为 200 OK

来自

IntegerField

price = models.DecimalField(max_digits=12,decimal_places=2)