Hamza Ince
Hamza Ince

Reputation: 684

Extract all fields from array with jq

I have a json file named collection.jsonsuch as :

{
    "info" : {
        ...
    },
    "item" : [
        {...}, # A
        {...}, # B
        {...}  # C
    ]

}

I want all the fields from the array item, like below:

{...}, # A
{...}, # B
{...}  # C

What I have tried:

jq -r '.item' collection.json

With this, I still avec the squares brackets, at the beginning and the end.

jq -r '.item[]' collection.json

With this, the comma between the fields is removed.

Upvotes: 0

Views: 1663

Answers (1)

pmf
pmf

Reputation: 36471

Since your expected output is neither valid JSON (which would be your first suggestion jq -r '.item' collection.json that includes commas AND the array brackets) nor the plain raw content of the elements (which would be your second suggestion jq -r '.item[]' collection.json that removes all the surrounding JSON syntax), you will have to build the desired syntax yourself which may depend on what the .item array elements actually are.

For instance, convert them into strings using tostring and glue them together with the join builtin:

jq -r '.item | map(tostring) | join(",\n")' collection.json

Upvotes: 3

Related Questions