我目前正在尝试解析给定的json文件:
{
"Level1": [
{
"Level2": [
{
"Level3-1": "ValueOfLevel3-1",
"Level3-2": [
{
"Value": "Value-01",
"Key": "Key01"
},
{
"Value": "Value-02",
"Key": "Key02"
}
]
}
]
},
{
"Level2": [
{
"Level3-1": "ValueOfLevel3-1",
"Level3-2": [
{
"Value": "Value-04",
"Key": "Key02"
},
{
"Value": "Value-03",
"Key": "Key01"
}
]
}
]
}
]
}
我们正在研究bash(任何像python这样的工具都可用)并且需要解析json文件以对" topid"的每次出现执行操作。
例如,只是粘贴" id"的值。和"关键"通过" echo"生成的命令应为:
echo "ValueOfLevel3-1" >> /tmp/file
echo "Value-02" >> /tmp/file
echo "ValueOfLevel3-1" >> /tmp/file
echo "Value-04" >> /tmp/file
虽然问题在于,它应该搜索正确的密钥名称 - 在本例中为keyname2
这样的事情可能吗?
干杯, 的Matthias
答案 0 :(得分:0)
搜索一下我发现: Parsing json and searching through it
解决方案 - 假设json包含在test.txt中:
import json
import sys
from pprint import pprint
with open('test.txt') as data_file:
data = json.load(data_file)
for c in data['Level1']:
for d in c.get('Level2'):
for f in d.get('Level3-2'):
if 'Key02' in f.get('Key'):
print d.get('Level3-1'), "\t", f.get('Value')
$ python runme2.py
ValueOfLevel3-1 Value-02
ValueOfLevel3-1 Value-04