【问题标题】:Python parsing json file to access values returning TypeErrorPython解析json文件以访问返回TypeError的值
【发布时间】:2019-01-18 15:51:25
【问题描述】:

我正在使用 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__'

所以我不确定如何在访问之前检查我尝试访问的记录是否存在,或者我什至是否以最正确的方式访问。谢谢。

【问题讨论】:

  • 据我了解,上面的数据是urldata。如果是这种情况,而不是 record["ips"][0]["geo"] 做 record["ips"]["geo"]。这应该有效。
  • 感谢您的反馈。这样做会给我一个错误:TypeError: list indices must be integers, not str 然而。

标签: python json typeerror


【解决方案1】:

您可以简单地检查record["ips"] 是否不是None,或者更简单地说是True,然后继续以列表的形式访问它;否则,您将在 None 对象上调用列表方法。

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

【讨论】:

  • 你是对的,这样做可以让我访问数据。现在它打印出很多数据,但随后给了我错误TypeError: string indices must be integers 我将继续调查此错误。我想你给我指明了一个好的方向。谢谢。
【解决方案2】:

因此,由于 json 文件的不一致性质,它最终有点令人费解,但我必须首先检查“ips”不为空,然后检查“geo”是否存在于记录中[“ips” "][0]。这是它的样子:

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

感谢大家的反馈!

【讨论】:

    猜你喜欢
    • 2013-10-25
    • 2021-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2017-07-16
    相关资源
    最近更新 更多