1

I need to flatten this json array of flat objects

[{
  "key1a": "value1",
  "key1b": "value2",
  ...
  "key1z": "value50",
},
{
  "key2a": "value2a",
  "key2b": "value2b",
  ...
  "key2y": "value2y",
},
{...},{...}]

to this csv style output

key1a+key1b+key1c... value1a|value1b|value1c...
key2a+key2b+key2c... value2a|value2b|value2c...

in order to do some post processing with awk.

I tried with ja functions map, add and flatten but did not succeed.

2 Answers 2

3

As the expected output is not CSV, I will not be using the @csv operator found in jq; instead, I will just naively insert the delimiters mentioned in the question. If any key or value in the input contains +, |, or space, these would need to be escaped appropriately in some extra processing step.

The keys may be joined together with + as the delimiter using the following jq expression:

.[] | keys | join("+")

The values may be joined together with | as the delimiter using the following jq expression:

.[] | [.[]] | join("|")

Joining the two key-and-values strings for each array element with a space as the delimiter:

.[] |
[
    ( keys  | join("+") ),
    ( [.[]] | join("|") )
] |
join(" ")

Testing this:

$ cat file.json
[
  {
    "key1a": "value1a",
    "key1b": "value2a",
    "key1z": "value50"
  },
  {
    "key2a": "value2a",
    "key2b": "value2b",
    "key2y": "value2y"
  }
]
$ jq -r '.[] | [ (keys | join("+")), ([.[]] | join("|")) ] | join(" ")' file.json
key1a+key1b+key1z value1a|value2a|value50
key2a+key2b+key2y value2a|value2b|value2y
1

Does this do the trick for you?

$ cat input.json | jq -r '.[] | to_entries | ([ .[].key ] | join("+")) + " " + ([ .[].value ] | join("|"))'
key1a+key1b+key1z value1a|value2a|value50
key2a+key2b+key2y value2a|value2b|value2y
$ cat input.json
[{
  "key1a": "value1a",
  "key1b": "value2a",
  "key1z": "value50"
},
{
  "key2a": "value2a",
  "key2b": "value2b",
  "key2y": "value2y"
}]

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .