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

5

我需要使用正则表达式解析JSON数组。我的JSON如下:

"keys": [
      {
        "host": "example.com"       
      },
      {
        "host": "example.net"
      }
    ]

我需要获取两个主机值。

1
如果它是正确的 JSON(例如,包装在 {} 中);你可以使用 jq -r '.keys[] | .host' - jfs
2个回答

10

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

grep -Po '(?<="host": ")[^"]*' myjsonFile

例如:

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

example.com
example.net

4
你能在这个答案中加更多的解释吗? - Sławosz
@Andy 需要 GNU Grep。 - Kent

1
以下正则表达式将使用非贪婪Kleene通配符获取您的主机值:
/"host":\s"(.*?)"/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接