【问题标题】:How to print json data in a post request in python3?如何在 python3 的 post 请求中打印 json 数据?
【发布时间】:2023-01-16 05:06:39
【问题描述】:

这是我的代码:

from requests import post

peer2profit = post("https://peer2profit.com/api/getpeers",data={"_token":"mytoken"}) 
print(peer2profit.json())

这是我期望的输出:

{
    "totalPeer": 10,
    "balance": 0.48045,
    "peers": [
        {
            "id": 108270438,
            "serial": null,
            "online": 1,
            "territorial_dispute": "",
            "version": "3.4bA",
            "platform": "ANDROID",
            "ip": "my ip",
            "country": "HR",

  And much more...

这是我得到的:

Traceback (most recent call last):
  File "c:\Users\skepp\Desktop\test.py", line 24, in <module>
    peer2profit = post("https://peer2profit.com/api/getpeers",headers={'accept': 'application/json'},data={"_token": "my token"}).json()['peers']
  File "C:\Users\skepp\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\models.py", line 910, in json
    return complexjson.loads(self.text, **kwargs)
  File "C:\Users\skepp\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:\Users\skepp\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\skepp\AppData\Local\Programs\Python\Python310\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我以前遇到过这个错误,但我不知道如何解决!

我在 2 个不同的 http 请求工具中尝试了这个 post 请求,它成功了!

这里有一些图片: RestMan Requestttp

【问题讨论】:

  • 也许你的要求不正确。您访问的API返回的状态(peer2profit.status)是什么?
  • 响应一如既往地是 200
  • 我有同样的错误,因为网站没有返回。我正在请求一个错误的 url,所以我修复了它

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


【解决方案1】:

我还想通过 python 和 json 检索 peer2profit 余额,你设法做到了吗?

感谢您的反馈和帮助。

【讨论】:

【解决方案2】:

我没有看到您已导入 JSON 并对其进行了解析。

from requests import post
import json

peer2profit = post("https://peer2profit.com/api/getpeers",data={"_token":"mytoken"}) 

# Parse it
parsed = json.loads(peer2profit)

# Output the entire dictionary 
print(parsed.json())

【讨论】:

  • 有问题的 json() 调用来自请求库
  • 现在我得到这个错误:Traceback(最近一次调用最后一次):文件“/root/EarningMonitor/test2.py”,第 37 行,在 <module> parsed = json.loads(peer2profit) File“/usr/lib/python3. 9/json/__init__.py", line 339, in loads raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not 响应
  • 您发送的某些请求具有数据类型 string 或 bool 但您将其作为 int 发送
猜你喜欢
  • 2014-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-22
  • 1970-01-01
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多