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": ")[^"]*'
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.
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.
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 .
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With