Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in shell script with regex

Tags:

json

shell

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.

like image 844
user1386776 Avatar asked Dec 17 '12 11:12

user1386776


People also ask

Can you parse JSON with regex?

With this information, it is possible to use regex to filter a JSON object to return the key, the value, and the parent object chain.


2 Answers

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
like image 94
Kent Avatar answered Nov 02 '22 11:11

Kent


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

/"host":\s"(.*?)"/
like image 21
Justin McDonald Avatar answered Nov 02 '22 10:11

Justin McDonald