【问题标题】:Trying to parse JSON data from a url with python尝试使用 python 解析来自 url 的 JSON 数据
【发布时间】:2019-07-12 02:23:34
【问题描述】:

我正在尝试通过 python 和 JSON API 制作 IP 详细信息抓取器,但我无法解析 JSON 数据。

我已经尝试加载和转储数据,但这些都不起作用,所以我对如何解析这些数据一无所知。

#Importing
import requests
import json
import os

#Variables
cls = os.system('cls')
#Startup

cls #Clearing the console on startup

ipToSearch = input("Please enter the IP you wish to search: ")
saveDetails = input("Would you like to save the IP's deatils to a file? Y/N: ")

ip_JSON = requests.get(url="http://ip-api.com/json/" + ipToSearch).json()
ip_Data = json.loads(ip_JSON)
print(ip_Data)

我正在尝试解析 IP 的信息,但结果是当前出现此错误。

Traceback (most recent call last):
  File "main.py", line 16, in <module>
    ip_Data = json.loads(ip_JSON)
  File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 341, 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 dict

【问题讨论】:

    标签: python json parsing url python-requests


    【解决方案1】:

    回溯是因为看起来您已经在上一行 .json() 将其转换为 json,然后您尝试再次执行此操作。

    ip_JSON = requests.get(url="http://ip-api.com/json/" + ipToSearch).json()
    ip_Data = json.loads(ip_JSON)
    

    试试

    ip_JSON = requests.get(url="http://ip-api.com/json/" + ipToSearch).json()
    print(ip_JSON)
    

    【讨论】:

    • 是的,我已经想通了。我只是想解析每个单独的 JSONstring,以便我可以将其写入/打印到控制台。
    【解决方案2】:

    试试 json.dumps,像这样

    ip_JSON = requests.get(url="http://ip-api.com/json/" + ipToSearch).json()
    ip_Data = json.dumps(ip_JSON)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-06
      相关资源
      最近更新 更多