简体   繁体   English

Grep 命令来自 json 文件 - Bash 脚本

[英]Grep command from json file - Bash scripting

My json file has the below content:我的 json 文件有以下内容:

{
  "Fruits": {
    "counter": 1,
    "protocols": [
      {
        "id": "100",
        "name": "lemon",
        "category": "citrus"
      },
      {
        "id": "350",
        "name": "Orange",
        "category": "citrus"
      },
      {
        "id": "150",
        "name": "lime",
        "category": "citrus"
      }
    ]
  }
}

I am expecting an output as below我期待 output 如下

Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus

Easy to do with jq :jq很容易做到:

$ jq -r '.Fruits.protocols[] | "Fruits:\(.name):\(.category)"' input.json
Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus

The jq answer is better. jq的答案更好。 Still posting a Ruby solution (if you cannot use jq), but it is less elegant:仍然发布 Ruby 解决方案(如果您不能使用 jq),但它不太优雅:

ruby -e '
  require "json";
  l="";
  ARGF.each { |x| l+=x };
  obj=JSON.parse(l);
  obj["Fruits"]["protocols"].each { |x| puts "Fruits:#{x["name"]}:#{x["category"]}" }
'

Here is the full example:这是完整的示例:

echo '{"Fruits":{"counter":1,"protocols":[{"id":"100","name":"lemon","category":"citrus"},{"id":"350","name":"Orange","category":"citrus" },{"id":"150","name":"lime","category":"citrus"}]}}' \
| ruby -e 'require "json";l="";ARGF.each { |x| l+=x } ; obj=JSON.parse(l) ; obj["Fruits"]["protocols"].each { |x| puts "Fruits:#{x["name"]}:#{x["category"]}" }'

Output: Output:

Fruits:lemon:citrus
Fruits:Orange:citrus
Fruits:lime:citrus

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM