(Python 新手) 我有一个 JSON 格式的多嵌套 dict,我正在尝试检查特定的键值是真还是假。我不确定检查嵌套在几个字典中的键的语法。我正在使用 URLVoid 的 API 的输出,它看起来像这样:
"data": {
"report": {
"dns_records": {
"ns": {
"records": [
{
"target": "alexis.ns.cloudflare.com",
"ip": "x.x.x.x",
"country_code": "US",
"country_name": "United States of America",
"isp": "CloudFlare Inc."
},
{
"target": "vida.ns.cloudflare.com",
"ip": "x.x.x.x",
"country_code": "JP",
"country_name": "Japan",
"isp": "CloudFlare Inc."
}
]
},
"mx": {
"records": []
}
},
"domain_blacklist": {
"engines": [
{
"name": "SpamhausDBL",
"reference": "https://www.spamhaus.org/lookup/",
"detected": false
},
{
"name": "ThreatLog",
"reference": "https://www.threatlog.com/",
"detected": false
},
{
"name": "OpenPhish",
"reference": "https://www.openphish.com/",
"detected": false
},
{
"name": "PhishTank",
"reference": "https://www.phishtank.com/",
"detected": false
},
{
"name": "Phishing.Database",
"reference": "https://github.com/mitchellkrogza/Phishing.Database",
"detected": false
},
{
"name": "PhishStats",
"reference": "https://phishstats.info/",
"detected": false
},
{
"name": "URLVir",
"reference": "https://www.urlvir.com/",
"detected": false
},
{
"name": "URLhaus",
"reference": "https://urlhaus.abuse.ch/",
"detected": false
},
{
"name": "RPiList Not Serious",
"reference": "https://github.com/RPiList/specials",
"detected": false
},
{
"name": "precisionsec",
"reference": "https://precisionsec.com/",
"detected": false
},
{
"name": "AntiSocial Blacklist",
"reference": "https://theantisocialengineer.com/",
"detected": false
},
{
"name": "PhishFeed",
"reference": "https://phishfeed.com/",
"detected": false
},
{
"name": "Spam404",
"reference": "https://www.spam404.com/",
"detected": false
},
{
"name": "CRDF",
"reference": "https://threatcenter.crdf.fr/check.html",
"detected": true
},
{
"name": "Artists Against 419",
"reference": "http://wiki.aa419.org/index.php/Main_Page",
"detected": false
},
{
"name": "CERT Polska",
"reference": "https://www.cert.pl/",
"detected": false
}
],
"detections": 1
为了测试,我将 JSON 保存在我的工作目录中。我试试
f = open("results.json", "r")
#print(f.read())
print(f.read()["data"]["reports"]["domain_blacklist"]["engines"][0])
错误:
Traceback (most recent call last):
File "directory/path", line 19, in <module>
print(f.read()["data"]["reports"]["domain_blacklist"]["engines"][0])
TypeError: string indices must be integers
遍历数据并检查 detected
的值是否为 true
的正确语法是什么?我理解一个简单的字典,如:
a_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}
我可以简单地做
for key in dict:
print key
但是因为这是多嵌套的,所以我迷路了。
答案 0 :(得分:2)
读取 JSON 文件后,您需要 json.load(fp)
将 fp
(包含 JSON 文档的文本对象或二进制文件)反序列化为 Python 对象。
import json
with open("results.json") as fp:
json_content = json.load(fp)
for engine in json_content["data"]["reports"]["domain_blacklist"]["engines"]:
print(engine["detected"])