Python解析json文件以访问返回TypeError的值
我正在使用python解析一个包含url数据的json文件,以尝试构建一个url信誉分类器。json文件中大约有2000个条目,但并非所有条目都包含所有字段。典型条目如下所示:Python解析json文件以访问返回TypeError的值,python,json,typeerror,Python,Json,Typeerror,我正在使用python解析一个包含url数据的json文件,以尝试构建一个url信誉分类器。json文件中大约有2000个条目,但并非所有条目都包含所有字段。典型条目如下所示: [ { "host_len" : 12, "fragment" : null, "url_len" : 84, "default_port" : 80, "domain_age_days" : "5621", "tld" : "com",
[
{
"host_len" : 12,
"fragment" : null,
"url_len" : 84,
"default_port" : 80,
"domain_age_days" : "5621",
"tld" : "com",
"num_domain_tokens" : 3,
"ips" : [
{
"geo" : "CN",
"ip" : "115.236.98.124",
"type" : "A"
}
],
"malicious_url" : 0,
"url" : "http://www.oppo.com/?utm_source=WeiBo&utm_medium=OPPO&utm_campaign=DailyFlow",
"alexa_rank" : "25523",
"query" : "utm_source=WeiBo&utm_medium=OPPO&utm_campaign=DailyFlow",
"file_extension" : null,
"registered_domain" : "oppo.com",
"scheme" : "http",
"path" : "/",
"path_len" : 1,
"port" : 80,
"host" : "www.oppo.com",
"domain_tokens" : [
"www",
"oppo",
"com"
],
"mxhosts" : [
{
"mxhost" : "mail1.oppo.com",
"ips" : [
{
"geo" : "CN",
"ip" : "121.12.164.123",
"type" : "A"
}
]
}
],
"path_tokens" : [
""
],
"num_path_tokens" : 1
}
]
我试图访问存储在“ips”和“mxhosts”字段中的数据,以比较“geo”位置。要尝试访问我使用的第一个“ips”字段,请执行以下操作:
corpus = open(file)
urldata = json.load(corpus, encoding="latin1")
for record in urldata:
print record["ips"][0]["geo"]
但正如我提到的,并非所有json条目都有所有字段。“ips”总是存在,但有时它是“null”,而“geo”也是如此。我试图在访问数据之前使用以下方法检查数据:
if(record["ips"] is not None and record["ips"][0]["geo"] is not None):
但我认为这是一个错误:
if(record["ips"] is not None and record["ips"][0]["geo"] is not None):
TypeError: string indices must be integers
当我尝试使用以下方法检查它时:
if("ips" in record):
我收到以下错误消息:
print record["ips"][0]["geo"]
TypeError: 'NoneType' object has no attribute '__getitem__'
因此,我不知道如何在访问之前检查我试图访问的记录是否存在,或者是否以最正确的方式访问。谢谢。您只需检查
记录[“ips”]
是否为无
,或者更简单地检查它是否为真
,然后将其作为列表访问;否则,您将对None
对象调用list方法
for record in urldata:
if record["ips"]:
print record["ips"][0]["geo"]
因此,由于json文件的不一致性,它最终变得有点复杂,但我必须首先检查“ips”是否为null,然后检查“geo”是否存在于记录[“ips”][0]中。这就是它看起来的样子:
if(record["ips"] is not None and "geo" in record["ips"][0]):
print record["ips"][0]["geo"]
谢谢大家的反馈 据我所知,上述数据是urldata。如果是这种情况,请不要记录[“ips”][0][“geo”]而要记录[“ips”][“geo”]。这应该行得通。谢谢你的反馈。这样做会产生错误:
TypeError:list索引必须是整数,而不是str
。这样做可以让我访问数据,这是正确的。现在它打印出了很多数据,但随后给了我一个错误TypeError:string索引必须是整数
,我将继续检查这个错误。我认为你给我指明了一个好的方向。谢谢