0

This is related to my previous question: How to use jq to format array of objects to separated list of key values

How can I (generically) transform the input file below to the output file below, using jq. The value at key "id" uniqely identifies the array element. The record format of the output file is: (value at key "id") | key | value.

I can do this if I add awk to solution of previous question, but I am having trouble getting my head around doing it all in jq.

Input file:

[{"id": 11, "b": 100},
 {"id": 12, "d": "fred", "e": 300}]

Output File:

11|id|11
11|b|100
12|id|12
12|d|fred
12|e|300

1 Answer 1

4

Here's a solution using to_entries, which decomposes an object into an array of key-value pairs:

jq -r '.[] | .id as $id | to_entries[] | [$id,.key,.value] | join("|")'
11|id|11
11|b|100
12|id|12
12|d|fred
12|e|300
Sign up to request clarification or add additional context in comments.

2 Comments

This is the exact same thing that I came up with.
This is a nice solution that has helped me learn jq

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.