使用正则表达式在shell脚本中解析JSON

use*_*776 5 shell json

我需要使用正则表达式解析jsonarray.我的json是

"keys": [
      {
        "host": "example.com"       
      },
      {
        "host": "example.net"
      }
    ]
Run Code Online (Sandbox Code Playgroud)

我需要获得两个主机值.

Ken*_*ent 10

当你想提取文字时,grep是你的朋友:

grep -Po '(?<="host": ")[^"]*' myjsonFile
Run Code Online (Sandbox Code Playgroud)

例如:

kent$  echo '"keys": [
      {
        "host": "example.com"       
      },
      {
        "host": "example.net"
      }
    ]'|grep -Po '(?<="host": ")[^"]*'

example.com
example.net
Run Code Online (Sandbox Code Playgroud)

  • 你能为这个anwser添加更多解释吗? (3认同)