Jq to extract particular value

Hello,

I am trying to use jq to extract the value of pci_slot from the following output

 # command_output
    {
      "binding_profile": "pci_slot='0000:12:13.6', pci_vendor_info='8086:10ed', physical_network='phys_sriov0'"
    }

Expected output:
0000:12:13.6

I'm not sure I understand the structure of this JSON. It seems binding_profile is a key, with multiple comma separated values. Do I need to convert this into a dictionary/array, where pci_slot is key, then get value via pci_slot[0] ?

# command_output | jq -r ".binding_profile"
    pci_slot='0000:12:13.6', pci_vendor_info='8086:10ed', physical_network='phys_sriov0'

Thanks.

Well first of all i'm no jq expert (used it really a bit..) but reading a manual and examples i came out with this :

<your output> | jq -r '.binding_profile |= split(",")[0] | .binding_profile |= split("=")[1] | .binding_profile' 

There is probably a shorter / better way, but i'm in the process of learning the tool myself.

Hope that helps
Regards
Peasant.

1 Like

Hi
And if you just apply the index?

jq -r '.binding_profile[10:22]'

or

jq -r '.binding_profile | [splits("=|, ?")][1]'

2 Likes

What about using jq only for the json and some other tool for the splitting?

   command_creating_json \
   | jq -r .binding_profile \
   | awk -F"'" '{print $2}' 
2 Likes

Then the command jg here is superfluous :smiley:

awk -F\' '/binding_profile/ {print $2}'

if the pipeline ends the line then escaping is not needed

command_creating_json |
jq -r .binding_profile |
awk -F"'" '{print $2}' 
3 Likes

Hi All,

Thanks for the responses. Ideally yes I would like to do this with one command. It seems that jq version 1.3 does not recognize split.

> # jq --version
> jq version 1.3
> 
> #  cmd | jq -r '.binding_profile[10:22]'
> jq: error: Cannot index string with object
> 
> #  cmd | jq -r '.binding_profile | [splits("=|, ?")][1]'
> error: splits is not defined
> .binding_profile | [splits("=|, ?")][1]
>                     ^^^^^^
> 1 compile error
> #  cmd | jq -r '.binding_profile |= split(",")[0] | .binding_profile |= split("=")[1] | .binding_profile'
> error: split is not defined
> .binding_profile |= split(",")[0] | .binding_profile |= split("=")[1] | .binding_profile
>                     ^^^^^
> error: split is not defined
> .binding_profile |= split(",")[0] | .binding_profile |= split("=")[1] | .binding_profile
>                                                         ^^^^^
> 2 compile errors

Seems split came with version 1.5. So you either upgrade or refrain from using split.

@nezabudka

Your version is shorter. I personally prefer the shown style with the | at the start of the line, because it shows visibly more clear for me that the current command is a continuation of the last line.

But there maybe other styles, with indentation for example...

command_creating_json |
     jq -r .binding_profile |
     awk -F"'" '{print $2}' 
3 Likes