尝试用python从API请求解析JSON

2024-05-14 10:04:45 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的密码

import requests
import json
api_get = requests.get('https://api.domainsdb.info/v1/domains/search?domain=dou.ua')
        api_answer = api_get.json()
        print(api_answer)

这就是答案

{'domains': [{'domain': 'dou.ua', 'create_date': None, 'update_date': '2019-01-08T12:41:02.907006', 'country': 'GB', 'isDead': 'False', 'A': ['178.79.140.30'], 'NS': ['ns3.linode.com', 'ns1.linode.com', 'ns2.linode.com', 'ns5.linode.com', 'ns4.linode.com'], 'CNAME': None, 'MX': [{'exchange': 'alt1.aspmx.l.google.com', 'priority': 1}, {'exchange': 'alt2.aspmx.l.google.com', 'priority': 1}, {'exchange': 'aspmx.l.google.com', 'priority': 0}], 'TXT': ['v=spf1 include:servers.mcsv.net ?all']}], 'total': 1, 'time': '771', 'next_page': None}

现在我需要重视“国家” 当我这么做的时候

import requests
import json
api_get = requests.get('https://api.domainsdb.info/v1/domains/search?domain=dou.ua')
api_answer = api_get.json()
country = json.loads(api_answer)
print(country["domains"]["country"])

我出错了

TypeError: the JSON object must be str, bytes or bytearray, not 'dict'

当我这么做的时候

import requests
import json
api_get = requests.get('https://api.domainsdb.info/v1/domains/search?domain=dou.ua')
api_answer = api_get.json()
country = json.dumps(api_answer)
print(country["domains"]["country"])

我出错了

  print(country["domains"]["country"])
TypeError: string indices must be integers

我不明白我要做什么。你知道吗


Tags: answerhttpsimportcomapijsongetdomain
2条回答

当你使用json.dumps文件返回的值是一个字符串,它是通过转储json形成的。您不能通过键来索引字符串,相反,您应该在本例中索引json ieapi_answer。你知道吗

import requests
import json
api_get = requests.get('https://api.domainsdb.info/v1/domains/search?domain=dou.ua')
api_answer = api_get.json()    
print(api_answer['domains'][0]['country'])

试试这个

import requests
import json
api_get = requests.get('https://api.domainsdb.info/v1/domains/search?domain=dou.ua')
api_answer = api_get.json()
print(api_answer['domains'][0]['domain'])

相关问题 更多 >

    热门问题