Search code examples
jsonkeyjq

How to get the json elements(key , value) in an object to be separated distinctly


I am facing an issue with the simple Json mentioned below where I am trying to separately extract "hello" and "world" from this and store them separately. This JSON is coming out after extraction of original data and finally in this format.

{
  "key": "hello",
  "value": "world"
}

I am using jq already so jq -r .key i am aware of already (same for value). But I don't want this to be separate step. What I want is something like this. Make a single call to the system that gives above json and store these "key" and "value" values in variables.

I very much appreciate help.


Solution

  • jq 1.7 introduced the --raw-output0 flag which "will print NUL instead of newline after each output". You can use this in combination with read and its -d flag with an empty string as argument which "will terminate a line when it reads a NUL character".

    $ { read -r -d '' key; read -r -d '' value; } < <(jq --raw-output0 '.key, .value' file.json)
    $ echo "$key"
    hello
    $ echo "$value"
    world
    

    With older versions of jq (1.5+), use the -j flag to omit the newlines, and print the NUL character manually using "\u0000":

    { read -r -d '' key; read -r -d '' value; } < <(jq -j '.key, .value | ., "\u0000"' file.json)
    $ echo "$key"
    hello
    $ echo "$value"
    world