skip to Main Content

I am jq from the terminal , to parse and filter the rest api using curl

below the response

{
    "result": [
        {
            "fxid": "03e401a",
            "id": "123"
        },
        {
            "fxid": "03e4099",
            "id": "567"
        },
        {
            "fxid": "867",
            "id": "666"
        }   
    ]
}

and. jq filter am using

.result[].fxid,.result[].id

and i got results as below

"03e401a" "03e4099" "867" "123" "567" "666"

but i want the filter results as follows , like grouping for each array element from json response , can anyone help me with this jq filter

"03e401a"
"123"
_________
"03e4099"
"567"
_______
"867"
"666"

Tried different jq filters , but nothing worked

3

Answers


  1. .result | map("(.fxid)n(.id)") | join("n------n")
    

    Will give

    03e401a
    123
    ------
    03e4099
    567
    ------
    867
    666
    

    When running jq with the --raw-output option.

    The idea is to concat id and fxid with a newline (n) and then join each item with some horizontal lines wrapped on newlines.


    Demo:
     [JqPlay Demo]

    Login or Signup to reply.
  2. ... | jq '.result[] | .fxid, .id, "_______"'
    
    "03e401a"
    "123"
    "_______"
    "03e4099"
    "567"
    "_______"
    "867"
    "666"
    "_______"
    
    Login or Signup to reply.
  3. With

    .result[].fxid, .result[].id
    

    you separately iterate twice over .result. Thus, , just then concatenates the two lists.

    Instead, iterate once, use a pipe to update the context, and just then concatenate the two (or more) items. That way, the iteration happens outside the concatenation:

    jq -r '.result[] | .fxid, .id'
    
    03e401a
    123
    03e4099
    567
    867
    666
    

    Demo

    To generate the blocks, just add more (static) items. For instance:

    jq -r '.result[] | .fxid, .id, "---"'
    
    03e401a
    123
    ---
    03e4099
    567
    ---
    867
    666
    ---
    

    Demo

    If you wanted to keep the JSON encoding for the values but not for the separators, use @json to re-encode them:

    jq -r '.result[] | (.fxid, .id | @json), "_________"'
    
    "03e401a"
    "123"
    _________
    "03e4099"
    "567"
    _________
    "867"
    "666"
    _________
    

    Demo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search