How to retrieve single value with grep from Json?

Viewed 58566

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": ")[^"]*'
6 Answers

The OP asks for solutions using grep. In case he means using terminal, the node cli is an alternative, since support for JSON is total. One alternative could be the command node --eval "script"

echo '{"key": 42}' \
| node -e console.log(JSON.parse(require("fs").readFileSync(0).toString()).key)' //prints 42
Related