0

I have a variable in script shell, when I execute echo $myvariable. this is the output :

         {"networks":[{"status":"ACTIVE","router:external":true,"availability_zone_hints":[],"availability_zones":["nova"],
"ipv4_address_scope":null,"description":"",
"port_security_enabled":true,**"subnets":["56efe610-32af-4f03-a73d-14bcbf1c9ae1","18ca945c-8868-4549-b725-e11f04612663"],**
    "updated_at":"2018-02-26T04:55:25Z",
    *"tenant_id":"187d635aec4c43fe8e8918afb3a5c82e",*
    "created_at":"2018-02-26T04:55:12Z",
    "tags":[],"ipv6_address_scope":null,
    "mtu":1500,"is_default":true,"revision_number":7,
    "admin_state_up":true,"shared":false,
    "project_id":"187d635aec4c43fe8e8918afb3a5c82e",
    "id":"7697d4c6-5b4c-4ea9-a1d6-af7d7f716f2b","name":"public"

Then I'm trying to extract the subnet id (56efe610-32af-4f03-a73d-14bcbf1c9ae1 and 18ca945c-8868-4549-b725-e11f04612663) and the tenant_id (187d635aec4c43fe8e8918afb3a5c82e).

I tried for tenant_id this shell script:

tenantid=$("$myvariable" | grep "tenant_id" | awk '{printf $2}')

echo $tenantid I get the same result.

For the subnets, I tried the same but I have same result.

subnets=$(echo "$myvariable" | grep "subnets" | awk '{printf $1}')

Thanks in advance guys.

Khalfe
  • 15
  • 2
  • 8

1 Answers1

0

This seems to work:

subnets=`echo $myvariable | egrep -o '"subnets":\[[-_A-Za-z0-9, "]*\]' | egrep -o '\[[-_A-Za-z0-9, "]*\]'`
tenant_id=`echo $myvariable | egrep -o '"tenant_id":"[-_A-Za-z0-9 ]*",'  | egrep -o ':"[-_A-Za-z0-9 ]*"' | egrep -o '"[-_A-Za-z0-9 ]*"'`

I don't know exactly which format you want.

brunorey
  • 2,135
  • 1
  • 18
  • 26
  • This is **very** fragile, and can break when seeing values that aren't in the expected format even if they're completely valid JSON. See [BashPitfalls #14](http://mywiki.wooledge.org/BashPitfalls#echo_.24foo) re: why even `echo $myvariable` is prone to misbehavior – Charles Duffy Mar 20 '19 at 20:24
  • Similarly, JSON can have a completely arbitrary number of spaces between `"subnets":` and the values that follow it -- or can have a newline between that key and the following value rather than whitespace on the same line at all. Or, for that matter, it can be `"subnets" :` with whitespace before the `:`. If you try to use syntax-unaware tools, you take the responsibility onto your code to correctly handle every possible permutation. – Charles Duffy Mar 20 '19 at 20:24
  • (Another corner case to test, which `egrep` and friends don't make it easy to handle, is `"value \"with quotes\""`) – Charles Duffy Mar 20 '19 at 20:28