RBB
RBB

Reputation: 874

How to iterate JSON content using jq in bash

I have a json content as below,

{
"Id": "Role1",
"Result": [
    {
        "Sub1": 1,
        "Sub2": 1,
        "StrSub": "ABC"
    },
    {
        "Sub1": 2,
        "Sub2": 1,
        "StrSub": "CDE"
    } ],
"Other": "NA"
}

I am trying to print as below,

Id
Result
Others

I could get the length by using jq length t1.json, but with the length I try to iterate the json file using --arg index 0 within a for loop, it doesn't work (jq --arg id 0 '.[$id]' t1.json)

Upvotes: 0

Views: 217

Answers (2)

Dmitry
Dmitry

Reputation: 1293

there's also an easy way to do it using a walk-path unix utility jtc:

bash $ <t1.json jtc -w'[:]<>k' 
"Id"
"Other"
"Result"
bash $ 

add -qq if you like to drop the quotes

PS> Disclosure: I'm the creator of the jtc - shell cli tool for JSON operations

Upvotes: 1

peak
peak

Reputation: 117017

Assuming the input has been rectified:

$ jq -r 'keys_unsorted[]' t1.json
Id
Result
Other

The reason jq --arg id 0 '.[$id]' t1.json does not work is that you've specified $id to be a JSON string.

The simplest way to pass in an integer argument is to use --argjson instead of --arg. One of many alternatives would be to use $id|tonumber instead of $id.

Upvotes: 2

Related Questions