Python解析json文件以访问返回TypeError的值

时间:2018-08-11 04:40:04

标签: python json typeerror

我正在使用python解析一个充满url数据的json文件,以尝试建立url信誉分类器。 json文件中大约有2,000个条目,但并非所有条目都包含所有字段。一个典型的条目如下所示:

[
   {
      "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__'

因此,我不确定在访问之前是否要检查要访问的记录是否存在,或者是否以最正确的方式访问。谢谢。

2 个答案:

答案 0 :(得分:1)

在继续作为列表访问之前,您可以简单地检查record["ips"]是否不是None,或更简单地检查它是否是True。否则,您将在None对象上调用列表方法。

for record in urldata:
    if record["ips"]:
        print record["ips"][0]["geo"]

答案 1 :(得分:0)

因此由于json文件的不一致特性,最终导致了一些麻烦,但是我不得不首先检查“ ips”是否不为空,然后检查记录“ ips”中是否存在“ geo” “] [0]。看起来像这样:

if(record["ips"] is not None and "geo" in record["ips"][0]):
                print record["ips"][0]["geo"]

感谢大家的反馈!