user1386776
user1386776

Reputation: 395

Parsing JSON in shell script with regex

I need to parse the jsonarray by using regex. My json is

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

I need to get the two hosts values.

Upvotes: 5

Views: 11076

Answers (2)

Kent
Kent

Reputation: 195029

When you want to extract text, grep is your friend:

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

For example:

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

example.com
example.net

Upvotes: 10

Justin McDonald
Justin McDonald

Reputation: 2166

The following regex will grab your host values using a non-greedy kleene wildcard:

/"host":\s"(.*?)"/

Upvotes: 1

Related Questions