Home > Mobile >  JQ: Convert Dictionary with List as Values to flat CSV
JQ: Convert Dictionary with List as Values to flat CSV

Time:11-19

Original Data

I have the following JSON:

{
    "foo":[
        "asd",
        "fgh"
    ],
    "bar":[
        "abc",
        "xyz",
        "ert"
    ],
    "baz":[
        "something"
    ]
}

Now I want to transform it to a "flat" CSV, such that for every key in my object the list in the value is expanded to n rows with n being the number of entries in the respective list.

Expected Output

foo;asd
foo;fgh
bar;abc
bar;xyz
bar;ert
baz;something

Approaches

I guess I need to use to_entries and then for each .value repeat the same .key for the first column. The jq docs state that:

Thus as functions as something of a foreach loop.

So I tried combining

  • to_entriesto give the keys and values from my dictionary an accessible name
  • then build kind of a foreach loop around the .values
  • and pass the result to @csv

to_entries|map(.value) as $v|what goes here?|@csv

I prepared something that at least compiles here

CodePudding user response:

Don't need to use _entries function, a simple key/value lookup and string interpolation should suffice

keys_unsorted[] as $k | "\($k);\( .[$k][])"

The construct .[$k][] is an expression that first expands the value associated with each key, i.e. .foo and then with object construction, produces multiple results for each key identified and stored in $k variable.

  • Related