skip to Main Content

I have this input data :

{
    "list": {
        "1": {
            "attributes": {
                "content": [],
                "pageable": {
                    "pageNumber": 0,
                    "pageSize": 10
                }
            }
        },
        "2": {
            "attributes": {
                "content": [
                    {
                        "id": "AZER"
                    }
                ],
                "pageable": {
                    "pageNumber": 0,
                    "pageSize": 10
                }
            }
        },
        "3": {
            "attributes": {
                "content": [
                    {
                        "id": "WXC"
                    },
                    {
                        "id": "QSD"
                    }
                ],
                "pageable": {
                    "pageNumber": 0,
                    "pageSize": 10
                }
            }
        }
    }
}

I need to use JQ to extract the id values into a new array, I try this:

.list[] | .attributes.content[].id

that’s my results:

"AZER"

"WXC"

"QSD"

It’s what i want but in 3 line and i need to have it in array
How can i make this results in an array like this:

["AZER","WXC","QSD"]

4

Answers


  1. just wrap you jq query with syntax [${request}]

    for sample

    jq '[.list[] | .attributes.content[].id]' input.json
    

    in your case the request became

    [.list[] | .attributes.content[].id]
    
    Login or Signup to reply.
  2. You can populate our own array:

    [ .[][].attributes.content[]?.id ]
    
    ["AZER","WXC","QSD"]
    

    Try it online

    Login or Signup to reply.
  3. In general, just wrap your query that produces a stream of the desired values into array brackets, and the output is an array of those values.

    [.list[] | .attributes.content[].id]
    

    Demo

    Note that there’s also a shortcut to [ .[] … ] called map(…):

    .list | map(.attributes.content[].id)
    

    Demo

    Both output:

    [
      "AZER",
      "WXC",
      "QSD"
    ]
    

    Use the --compact-output (or -c) flag, to remove irrelevant whitespace, thus compacting the output into a single line: ["AZER","WXC","QSD"]

    Login or Signup to reply.
  4. If you just want to extract all "id" values into an array, streaming is also an option.

    [ tostream | select((.[0][-1]=="id") and (.|length==2)) | .[1] ]
    

    Try it on jqplay.org.

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