【问题标题】:Enumerate JSON return枚举 JSON 返回
【发布时间】:2015-11-28 04:45:29
【问题描述】:

如何枚举 JSON 返回?目标是获得一个总计数变量以添加到我的打印语句中......

我有

for i in services_js["reports"]:
            print " Service Name: " + i["instances"]["serviceName"]

并尝试过:

for i in enumerate(services_js["reports"]):
            print " Service Name: " + i["instances"]["serviceName"]

但得到:

TypeError: tuple indices must be integers, not str

【问题讨论】:

  • 很大程度上取决于services_js的结构。愿意给我们看一个例子吗?
  • 不幸的是,我的循环无法正常工作...当我尝试使用计数器执行此操作时,它会变为 1,2,3,1,2,3,1,2,3... 因为services_js 是一个 URL 列表 services_js = json.loads(services_open.read())
  • 如果services_js 是一个列表,那么services_js["reports"] 将不起作用,因为您不能用字符串索引列表。
  • 字典*...它确实有效
  • 好的。如果i["instances"] 是一个元组,那么i["instances"]["serviceName"] 将不起作用,因为你不能用字符串索引一个元组。

标签: python json python-2.7 loops enumerate


【解决方案1】:

enumerate 不是这样工作的:

for i in enumerate(services_js["reports"]):
    print " Service Name: " + i["instances"]["serviceName"]

它是这样工作的:

animals = ['rat', 'cat', 'mouse', 'dog']
for i, animal in enumerate(animals, start=1):
    print('# {}: {}'.format(i, animal))

注意enumerate 如何返回一个元组,(ianimal只是计数?

您可能有其他问题(在您的 JSON 中),但那部分可能会让您失望。

您看到的错误是因为i 实际上是元组(0, some_json),然后您尝试执行i['instance'],所以它说您不能使用字符串作为元组的索引。

【讨论】:

    【解决方案2】:

    如果没有看到 JSON 的结构,很难确定,但根据键名,您可能想要

    count = 0
    for report in services_js["reports"]:
        for instance in report["instances"]:
            count += 1
            print "Service Name: " + instance["serviceName"]
    print "there were {} total instances".format(count)
    

    【讨论】:

    • print statment 上仍然得到TypeError: string indices must be integers
    • 那我猜错了你的JSON的结构,此时也无能为力了。对不起。
    猜你喜欢
    • 2019-08-06
    • 2012-11-27
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多