【问题标题】:Invalid Json while using get requests Flask使用获取请求 Flask 时 Json 无效
【发布时间】:2020-04-06 13:15:27
【问题描述】:

我需要通过 API 请求一个 PG 数据库,我正在使用 Flask requests 包:

 payload = {'key':'**', 'schema':'**', 'table':'testh','where_clause':'0', 'liste_fields':'*'}
r = requests.get('https://myapi/', params=payload, verify=False)   

我需要在 JSON 中获取我的 testh 表存储的所有内容,但函数 r.json() 让我得到这个无效的 JSON:

{'id': {'0': '1', '1': '2', '2': '3', '3': '4'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}

我需要一个 JSON 格式:{0: {id:'2', brand:'apple}, 1:{id:'2', brand:'microsoft}, ....}

【问题讨论】:

    标签: json flask python-requests


    【解决方案1】:

    您可以为此使用 pandas:

    import pandas as pd
    d = {'id': {'0': '1', '1': '2', '2': '3', '3': '4'}, 'brand': {'0': 'apple', '1': 'microsoft', '2': 'google', '3': 'amazon'}}
    d = pd.DataFrame(d).to_dict(orient='index')
    

    输出:

    {'0': {'id': '1', 'brand': 'apple'},
     '1': {'id': '2', 'brand': 'microsoft'},
     '2': {'id': '3', 'brand': 'google'},
     '3': {'id': '4', 'brand': 'amazon'}}
    

    这只是一个猜测,但也许 API 也使用了 pandas,如果你在没有参数的情况下调用 to_dict(),你会得到你所描述的输出。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-07
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多