Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to retrieve single value with grep from Json?

Tags:

How to extract a single value from a given json?

{
  "Vpc": {
    "InstanceTenancy": "default", 
    "State": "pending", 
    "VpcId": "vpc-123", 
    "CidrBlock": "10.0.0.0/16", 
    "DhcpOptionsId": "dopt-123"
  }
}

Tried this but with no luck:

grep -e '(?<="VpcId": ")[^"]*'
like image 821
Centurion Avatar asked Mar 17 '16 23:03

Centurion


People also ask

How do you get a specific value from a JSON string?

Use a JSON library to parse the string and retrieve the value. The following very basic example uses the built-in JSON parser from Android. String jsonString = "{ \"name\" : \"John\", \"age\" : \"20\", \"address\" : \"some address\" }"; JSONObject jsonObject = new JSONObject(jsonString); int age = jsonObject.

Can you grep a JSON file?

grep is the standard unix tool to filter text files and will remain the standard tool because of its speed and many examples available online, but grep its not well suited to parse JSON because it doesnt do any filtering between key and values of JSON.

Can JSON be a single value?

JSON data, at its simplest, can be a single object composed of fields, with each field having a simple value. Some terminology: A value can be a simple value, an array, or an object. A simple value can be a string, a number, or a Boolean value true or false , or null .

How do I use grep search?

To search multiple files with the grep command, insert the filenames you want to search, separated with a space character. The terminal prints the name of every file that contains the matching lines, and the actual lines that include the required string of characters. You can append as many filenames as needed.


1 Answers

You probably wanted -Po, which works with your regex:

$ grep -oP '(?<="VpcId": ")[^"]*' infile
vpc-123

If GNU grep with its -P option isn't available, we can't use look-arounds and have to resort to for example using grep twice:

$ grep -o '"VpcId": "[^"]*' infile | grep -o '[^"]*$'
vpc-123

The first one extracts up to and excluding the closing quotes, the second one searches from the end of the line for non-quotes.

But, as mentioned, you'd be better off properly parsing your JSON. Apart from jq mentioned in another answer, I know of

  • Jshon
  • JSON.sh

A jq solution would be as simple as this:

$ jq '.Vpc.VpcId' infile 
"vpc-123"

Or, to get raw output instead of JSON:

$ jq -r '.Vpc.VpcId' infile 
vpc-123
like image 83
Benjamin W. Avatar answered Oct 15 '22 03:10

Benjamin W.