遍历json元素以获取值列表

时间:2018-07-20 04:17:41

标签: python

我有以下代码:

#!/usr/bin/python2.7
import json, re, sys
x = json.loads('''{"status":{"code":"200","msg":"ok","stackTrace":null},"dbTimeCost":11,"totalTimeCost":12,"hasmore":false,"count":5,"result":[{"_type":"Compute","_oid":"555e262fe4b059c7fbd6af72","label":"lvs3b01c-ea7c.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27d8e4b059c7fbd6bab9","label":"lvs3b01c-9073.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27c9e4b059c7fbd6ba7e","label":"lvs3b01c-b14b.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2798e4b0800601a83b0f","label":"lvs3b01c-6ae2.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2693e4b087582f108200","label":"lvs3b01c-a228.stratus.lvs.ebay.com"}]}''')
print x['result'][4]['label']
sys.exit()

期望的结果应该是所有标签。但是,当我运行它时,它仅打印第一个标签。我在这里做什么错了?

而且,在我弄清楚“结果”是要使用的关键之前,我需要将json数据复制并粘贴到“ jsonlint.com”之类的站点中,以便以可读的方式重新格式化它。我想知道是否有更好的方法,最好不必在任何地方复制和粘贴json数据。

有两个问题:

  1. 如何获取上面的代码以列出所有标签
  2. 我如何知道我想要的字段的密钥,而不必重新格式化给定的难看的一个线性json数据

3 个答案:

答案 0 :(得分:2)

只需更改用于打印标签的代码

print x['result'][4]['label'] # here you are just printing the 4th label only

 print [i["label"] for i in x['result']]

答案 1 :(得分:1)

您需要循环所有结果。您得到的是带有标签的对象列表。

labels = [ i.get('label') for i in x.get('result')]
print(labels)

使用.get(),如果密钥不可用,则不会返回None。

答案 2 :(得分:0)

使用列表推导来获取所有标签

例如:

override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    print(indexPath.item)
    viewController?.pushView()
}

func pushView() {
    let controller = UINavigationController(rootViewController: DetailController())
    self.navigationController?.pushViewController(controller, animated: true)
}

输出:

import json, re, sys
x = json.loads('''{"status":{"code":"200","msg":"ok","stackTrace":null},"dbTimeCost":11,"totalTimeCost":12,"hasmore":false,"count":5,"result":[{"_type":"Compute","_oid":"555e262fe4b059c7fbd6af72","label":"lvs3b01c-ea7c.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27d8e4b059c7fbd6bab9","label":"lvs3b01c-9073.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e27c9e4b059c7fbd6ba7e","label":"lvs3b01c-b14b.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2798e4b0800601a83b0f","label":"lvs3b01c-6ae2.stratus.lvs.ebay.com"},{"_type":"Compute","_oid":"555e2693e4b087582f108200","label":"lvs3b01c-a228.stratus.lvs.ebay.com"}]}''')
print [i["label"] for i in x['result']]
sys.exit()

您可以使用[u'lvs3b01c-ea7c.stratus.lvs.ebay.com', u'lvs3b01c-9073.stratus.lvs.ebay.com', u'lvs3b01c-b14b.stratus.lvs.ebay.com', u'lvs3b01c-6ae2.stratus.lvs.ebay.com', u'lvs3b01c-a228.stratus.lvs.ebay.com'] 来以更好的格式查看JSON。

例如:

pprint

输出:

import pprint
pprint.pprint(x)
相关问题