如何遍历JSON数组?

时间:2018-11-11 20:08:45

标签: python json loops

我有这个具有多个根的JSON数组:

[
  {
  "issuer_ca_id": 16418,
  "issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
  "name_value": "sub.test.com",
  "min_cert_id": 325717795,
  "min_entry_timestamp": "2018-02-08T16:47:39.089",
  "not_before": "2018-02-08T15:47:39"
  },
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]

我想遍历它并在Python中打印issuer_name值。有什么解决办法吗?

1 个答案:

答案 0 :(得分:0)

使用json包并加载json。假设它是内存中的字符串(与.json文件相对):

jsonstring = """
[
  {
  "issuer_ca_id": 16418,
  "issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
  "name_value": "sub.test.com",
  "min_cert_id": 325717795,
  "min_entry_timestamp": "2018-02-08T16:47:39.089",
  "not_before": "2018-02-08T15:47:39"
  },
{
"issuer_ca_id":9324,
"issuer_name":"C=US, O=Amazon, OU=Server CA 1B, CN=Amazon",
"name_value":"marketplace.test.com",
"min_cert_id":921763659,
"min_entry_timestamp":"2018-11-05T19:36:18.593",
"not_before":"2018-10-31T00:00:00",
"not_after":"2019-11-30T12:00:00"
}
]"""

import json
j = json.loads(jsonstring)
[item["issuer_name"] for item in j]

礼物:

["C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
 'C=US, O=Amazon, OU=Server CA 1B, CN=Amazon']

现在,这些名称对我来说似乎不像是名字,但这是分配给issuer_name字段的内容,所以我认为这是您必须与数据所有者联系的地方。

如果是文件,请按照以下基本模式进行加载:

# something like this
with open("jsonfile.json", "rb") as fp:
    j = json.load(fp) 

在此处查看文档:{​​{3}}