Awk

來自 json 文件的 Grep 值

  • July 23, 2021

我的 json 文件看起來像這樣

[{"product":"Apple","id":"2134"},{"product":"Mango","id":"4567"}]

我想為給定的“產品”grep/sed/awk“id”。

輸出:

Enter product : Apple
Your product id is : 2134

使用 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";

使用json解析器,而不是sed// grepawk

使用 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

引用自:https://unix.stackexchange.com/questions/259597