I have a JSON document that looks like this
[
{
"id": "bbb",
"lines": [
"bla bla bla"
],
},
{
"id": "ccc",
"lines": [
"lorem ipsum",
"sample text"
]
}
{
"id": "ddd",
"lines": [
"foo"
]
},
{
"id": "eee",
"lines": [
"some text",
"some more text",
"foobar"
]
}
]
I am attempting to use jq
to modify this document into something that looks like this:
{
"bbb_0": "bla bla bla",
"ccc_0": "lorem ipsum",
"ccc_1": "sample text",
"ddd_0": "foo",
"eee_0": "some text",
"eee_1": "some more text",
"eee_2": "foobar"
}
How would I achieve this? Thanks!
CodePudding user response:
You could use with_entries
to convert the array into an object with defined keys, and reduce
to construct the overall object:
jq '
reduce .[] as {$id, $lines} ({};
. ($lines | with_entries(.key |= "\($id)_\(.)"))
)
'
{
"bbb_0": "bla bla bla",
"ccc_0": "lorem ipsum",
"ccc_1": "sample text",
"ddd_0": "foo",
"eee_0": "some text",
"eee_1": "some more text",
"eee_2": "foobar"
}
CodePudding user response:
Another way of achieving the desired output, using map
, with_entries()
and add
:
map(.id as $id | .lines | with_entries(.key |= "\($id)_\(.)")) | add
Produces
{
"bbb_0": "bla bla bla",
"ccc_0": "lorem ipsum",
"ccc_1": "sample text",
"ddd_0": "foo",
"eee_0": "some text",
"eee_1": "some more text",
"eee_2": "foobar"
}
Aa you can test in this online demo