2

I'm trying to print the json output using jq, But I'm getting null How can I print only access_key and secret_key, but not null?

$ cat sample.json | jq '.'

{
  "access_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}
{
  "secret_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}

$ cat sample.json | jq -e ".access_key"  
xxxxxxxxxxxxxxxxxxxxxxxxx
null

The same happens with secret_key.

If I use "raw output", I get an error:

$ cat sample.json | jq -r ".access_key" | jq --raw-output 'select(type == "string")'
parse error: Invalid numeric literal at line 2, column 0

I tried this also:

$ cat sample.json | jq -re ".access_key" | jq 'select(.go != null) | .geo' > geo-only.json
parse error: Invalid numeric literal at line 2, column 0
3

Your input is not valid json. You can use https://jsonlint.com to check.

You could make it valid by changing it to something like:

[{
    "access_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}, {
    "secret_key": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
}]

Or jq has a workaround for this:

cat sample.json | jq "..|objects|select(.access_key) | .access_key"

I recommend using a tool simply called json over jq. It's not as fast but it's much more intuitive to use and has better features.

json handles this with the -g argument:

-g, --group

Group adjacent objects into an array of objects, or concatenate adjacent arrays into a single array.

$ cat sample.json | json -ag access_key
1234
| improve this answer | |
0

a solution is to use empty

cat sample.json | jq -r -e ".access_key // empty "
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.