【问题标题】:Python: request json gets error - If using all scalar values, you must pass an indexPython:请求 json 出错 - 如果使用所有标量值,则必须传递索引
【发布时间】:2021-08-01 05:53:15
【问题描述】:

当尝试从 API 请求 json 文件时,我在得到第一个结果后出现错误。

有人知道为什么要从列表中获取索引吗?

最好的问候:)

import requests
import json
import pandas as pd
import time
import datetime

### OCs List ids
OCs = ['1003473-1116-SE21','1003473-1128-AG21','1031866-12-CC21','1057440-3184-AG21','1070620-1832-CM21', '1070620-2219-SE21', '1070620-2499-CM21']

for i in OCs:
    link ="http://api.mercadopublico.cl/servicios/v1/publico/ordenesdecompra.json?codigo="+ str(i) +"&ticket=F8537A18-6766-4DEF-9E59-426B4FEE2844"
    response = requests.get(link, [])
    data = response.json()
    
    df = pd.DataFrame.from_dict(data) 
    
    ### remove unnecessary columns
    df.drop(df.columns[[0,1,2]],axis=1, inplace=True)
         
    ### flat json to pandas dataframe
    df_detail = pd.json_normalize(df['Listado'])


ValueError: If using all scalar values, you must pass an index
 

【问题讨论】:

    标签: json python-3.x pandas list python-requests


    【解决方案1】:

    服务器检测到太多请求并发送错误响应(然后您的脚本抛出错误)。解决方法是等待正确响应,例如:

    import requests
    import json
    import pandas as pd
    import time
    import datetime
    
    ### OCs List ids
    OCs = [
        "1003473-1116-SE21",
        "1003473-1128-AG21",
        "1031866-12-CC21",
        "1057440-3184-AG21",
        "1070620-1832-CM21",
        "1070620-2219-SE21",
        "1070620-2499-CM21",
    ]
    
    for i in OCs:
        link = (
            "http://api.mercadopublico.cl/servicios/v1/publico/ordenesdecompra.json?codigo="
            + str(i)
            + "&ticket=F8537A18-6766-4DEF-9E59-426B4FEE2844"
        )
    
        while True:   # <--- repeat until we get correct response
            print(link)
            response = requests.get(link, [])
            data = response.json()
    
            if "Listado" in data:
                break
    
            time.sleep(3)   # <--- wait 3 seconds and try again
    
        df = pd.DataFrame.from_dict(data)
    
        ### remove unnecessary columns
        df.drop(df.columns[[0, 1, 2]], axis=1, inplace=True)
    
        ### flat json to pandas dataframe
        df_detail = pd.json_normalize(df["Listado"])
    
        # ...
    

    【讨论】:

      猜你喜欢
      • 2017-02-19
      • 2020-03-19
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 2018-05-29
      • 2021-07-14
      相关资源
      最近更新 更多