【问题标题】:Accessing data from a json array in python JSONDecodeError at /get/从 /get/ 的 python JSONDecodeError 中的 json 数组访问数据
【发布时间】:2020-09-15 10:10:15
【问题描述】:

我的回复如下:

[
 {"_id":"5f6060d0d279373c0017447d","name":"Faizan","email":"faizan@test.com"}
]

我想在 python 中获取名称。我正在尝试:

response = requests.get(url)
data = response.json()

我得到的错误是: /get/处的 JSONDecodeError

【问题讨论】:

  • 什么是response.text 内容,同时发布完整的引用
  • 你是说使用 response.text() 而不是 response.json() 吗?
  • 不,我是说要调试您的代码并通过查看 response.text 来查看它返回的内容,同时发布问题执行 stackoverflow.com/help/minimal-reproducible-example 并发布完整的回溯

标签: python django


【解决方案1】:

这可能对你有帮助

import requests
import json
dburl = 'https://postman-9e13.restdb.io/rest/contact'
headers = {'x-apikey': '7267cbb3c251a01dd8563ca447194e78af67d', 'Content-Type': 'application/json'}
params = {"name":"Faizan","email":"faizan@test.com"}
r = requests.get(dburl, params=params, headers=headers)
print(r.json())

看到结果后,你可以像这样传递给你的模板

geodata = response.json() 
return render(request, 'main/get.html', { 'name': geodata[0]['name'] })

或者你可以相应地改变。

【讨论】:

    【解决方案2】:

    您分享的 sn-p 是正确的,但问题可能出在 URL 上。

    response = requests.get(url)
    data = response.json()
    

    这里,.json() 仅适用于 JSON 格式的响应。如果它显示该错误,则意味着您的 URL 返回了 HTML 文档。

    【讨论】:

    • 我的网址是:postman-9e13.restdb.io/rest/contact?q={"name":"Faizan","email":"faizan@test.com"} 返回一个 json
    • postman-9e13.restdb.io/rest/contact?q={"name":"Faizan","email":"faizan@test.com"} 当我访问这个时链接它向我显示此行 无法访问。代码 001 ,您可以使用 response.text 查看您的 URL 返回的内容。
    • 奇怪的东西!我正在使用restdb.io,并且该链接仅在我登录站点restdb.io的浏览器中有效
    • 您尝试过使用 response.text 吗?
    • 是的,我得到错误:'str' object is not callable
    猜你喜欢
    • 1970-01-01
    • 2017-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多