我要将JSON转换为字典,然后直接访问值。这是JSON:
{
"timestamp": {
"format": "%Y-%m-%d %H:%M:%S"
},
"status": {
"grok_pattern": " status=%{NUMBER:status:int}"
},
"SQLite3_memory_bytes": {
"table": "stats_memory_metrics",
"saved_name": "sqlite3_memory_bytes"
},
"jemalloc_resident": {
"table": "stats_memory_metrics"
}
}
我可以很好地访问单个嵌套字典,但是当我尝试使用多个键访问嵌套字典时,出现错误:
with open('/tmp/metrics.json') as json_file:
patterns = json.load(json_file)
print(patterns['jemalloc_resident']['table'])
print(patterns['timestamp']['format'])
print(patterns['SQLite3_memory_bytes']['saved_named'])
>> stats_memory_metrics
>> %Y-%m-%d %H:%M:%S
>> Traceback (most recent call last):
>> File "test.py", line 12, in <module>
print(patterns['SQLite3_memory_bytes']['saved_named'])
KeyError: 'saved_named'
如何访问saved_named密钥的值?
答案 0 :(得分:1)
您打错了字。您放置了len=5 cap=5 [[1 2] [2 3] [3 4] [1 4] [1 5]]
len=5 cap=5 [[2 3] [3 4] [1 4] [1 5] [1 5]]
而不是saved_named
。