【发布时间】:2020-04-24 21:29:50
【问题描述】:
实际的 Json 是:
{
"title1": {
"titleID": "1234",
"titlename": "a-b-c",
},
"title2": [
{
"block": "0.0.0.0/26",
"abc_id": "abc-0123",
"tags": [{ "key": "Name", "value": "abc-name"},
{ "key": "env", "value": "dev"}]
},
{
"block": "1.2.0.0/26",
"abc_id": "abc-4567"
},
{
"block": "0.0.0.0/26",
"abc_id": "abc-8999",
"tags": [{ "key": "Name", "value": "xyz-name"}]
},
{
"block": "0.0.0.0/26",
"abc_id": "abc-7766",
"tags": [{ "app": "Name", "value": "web-app"}]
}
]
}
我的代码是
with open('/tmp/temp.json') as access_json:
read_content = json.load(access_json)
for key1, value1 in read_content.items():
if key1 == "title1":
title_id = value1['titleID']
if key1 == "title2":
title2_access = read_content['title2']
for title2_data in title2_access:
for key2, value2 in title2_data.items():
if key2 == "abc_id":
abc_id = value2
if key2 == "tags":
tags_access = read_content['tags']
for tags_data in tags_access:
for key3, value3 in tags_data.items():
if key3 == "Name":
abc_name = value3
错误是:
Traceback (most recent call last):
File "/tmp/runscript.py", line 123, in <module>
runpy.run_path(temp_file_path, run_name='__main__')
File "/usr/local/lib/python3.6/runpy.py", line 263, in run_path
pkg_name=pkg_name, script_name=fname)
File "/usr/local/lib/python3.6/runpy.py", line 96, in _run_module_code
mod_name, mod_spec, pkg_name, script_name)
File "/usr/local/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: 'tags'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/tmp/runscript.py", line 142, in <module>
raise e_type(e_value).with_traceback(new_stack)
File "/tmp/glue-python-scripts-lw031e0z/tsf_dev.py", line 160, in <module>
KeyError: KeyError('tags',)
原因:title2 字典中的所有项目都不包含“标签”。所以,如果没有 'tags' 或 tags['name'],那么 abc_name = ''
我需要列表列表 (titleID, abc_id, abc_name).
预期输出:
['1234','abc-0123','abc-name']
['1234','abc-4567','']
['1234','abc-8999','xyz-name']
['1234','abc-7766','']
有一个“title2”的字典, 它包含 abc_id 并且少数项目也包含“标签”。 如果没有标签,那么 abc-name 应该是 ''。 如果没有 Key:"name",那么 abc-name 应该是 ''。 如果字典中有标签和 key: "name",那么 abc-name 应该是 title2[tags][value: ""] 中存在的值,其中 title2[tags][key is "name"]
【问题讨论】:
-
你认为的变量“read_content”是什么?
-
你的预期输出是什么?
-
或
tags['name'],这是什么意思?代码中的任何地方都没有这样的键 -
请将完整错误消息编辑到您的问题中。
-
为什么不做一些简单的调试:在每个
for循环中添加一些打印语句,以便查看影响代码的变量值?异常之前的打印输出将帮助您找出问题所在。
标签: python json list for-loop if-statement