我有一个json内容(output.json)
{"project": {"id": "A", "content": [{"name": "XYZ", "location": "Berlin", "comments":""}, {"name": "ABC", "location": "NewYork", "comments": "Hwllo"}, {"name": "DEF", "location": "Paris", "comments": "Success"}]}}
我想使用bash或shell命令从上述json中匹配location
说name
时提取具有值的ABC
键
我尝试了下面类似的方法,使花括号内的内容变得令人满意。但不确定是否要搜索特定键。
cat output.json | grep -o -e "{.*}"
输出期望:
如果name
与ABC
相匹配,则输出为"location":"NewYork"
关于进一步处理的任何建议吗?
答案 0 :(得分:0)
这里可能有更好的方法,这里有一种快速的方法。
cat output.json | sed 's/"name"/\n"name"/g' | grep '"name"' | awk -F',' '{print $2}'
如果需要根据名称进行过滤,还添加| grep <preferred name>
。
答案 1 :(得分:0)
如果要从json中提取,则应使用jq。根据作者的说法,“ jq就像sed一样用于JSON数据” (source)。
您的情况应该是:
NewYork
输出将是:
"location":"NewYork"
要获得所需的输出,
echo "\"location\":$(jq -r '.project' output.json | jq -r '.content' | jq '.[] | select(.name=="ABC")' | jq '.location')"
您可以使用:
$ sudo apt install jq
在使用jq之前,应先将其安装在Debian和Ubuntu上:
$("img[data-src]")
对于其他操作系统,您应该选中this site。
答案 2 :(得分:0)
使用Perl
$ perl -0777 -lne ' while(/"name":\s+"ABC",\s+"location":\s+(\S+)/msg) { print "$1\n" } ' output.json
"NewYork",
$ cat output.json
{"project": {"id": "A", "content": [{"name": "XYZ", "location": "Berlin", "comments":""}, {"name": "ABC", "location": "NewYork", "comments": "Hwllo"}, {"name": "DEF", "location": "Paris", "comments": "Success"}]}}
$
答案 3 :(得分:0)
请使用JSON解析器处理JSON。
使用Xidel,它很简单:
xidel -s output.json -e '($json//content)()[name="ABC"]/location'
或者:
xidel -s output.json -e '$json/(.//content)()[name="ABC"]/location'
or in full:
xidel -s output.json -e '$json/project/(content)()[name="ABC"]/location'
以上是XPath表示法(example #11, Reading JSON)。点符号(例如jq
)也是可能的:
xidel -s output.json -e '($json).project.content()[name="ABC"].location'
[编辑]
上面的命令发出了NewYork
,我才刚刚意识到您需要输出为"location":"NewYork"
。 Xidel也可以做到这一点:
xidel -s output.json -e '($json//content)()[name="ABC"]/concat("""location"":""",location,"""")'
[/ edit]