我的 json 文件看起来像这样
[{"product":"Apple","id":"2134"},{"product":"Mango","id":"4567"}]
我想 grep/sed/awk 'id' 来查找给定的“产品”。
输出:
Enter product : Apple
Your product id is : 2134
答案1
使用 JSON 感知工具。 Perl 有JSON图书馆:
#!/usr/bin/perl
use warnings;
use strict;
use JSON;
my $json = '[{"product":"Apple","id":"2134"},{"product":"Mango","id":"4567"}]';
print 'Enter product: ';
chomp( my $product = <> );
print 'Your product id is: ',
(grep $_->{product} eq 'Apple', @{ from_json($json) })[0]{id}, "\n";
答案2
使用json
解析器,而不是sed
// grep
。awk
使用Pythonjson
模块:
#!/usr/bin/env python2
import json
with open('file.json') as f:
f_json = json.load(f)
print 'Enter product : ' + f_json[0]['product'] + '\nYour product id is : ' + f_json[0]['id']
输出:
Enter product : Apple
Your product id is : 2134
答案3
我创建了一个名为 json 的文件,如下所示:
[{"product":"Apple","id":"2134"},{"product":"Mango","id":"4567"},{"product":"Pear","id":"1111"},{"product":"Banana","id":"2222"}]
然后我在命令行上运行:
cat json | sed -e 's/.\?{"product"\:\"\([^\"]\+\)\","id"\:\"\([[:digit:]]\+\)[^}]}\+.\?/Enter Product : \1\nYour Product id is : \2\n/mgi'
输出是这样的:
Enter Product : Apple
Your Product id is : 2134
Enter Product : Mango
Your Product id is : 4567
Enter Product : Pear
Your Product id is : 1111
Enter Product : Banana
Your Product id is : 2222
答案4
给定 中的产品名称,可以使用如下方式$name
解析该产品的 ID :jq
jq -r --arg name "$name" '.[] | select(.product == $name).id' file.json
例子:
$ cat file.json
[{"product":"Apple","id":"2134"},{"product":"Mango","id":"4567"}]
$ name=Apple
$ jq -r --arg name "$name" '.[] | select(.product == $name).id' file.json
2134