I would like to flatten a json file in order to meet the needs of a legacy program. I would prefer to use jq for this as I know it is available to me.
I have a file something like this:
[
{
"field1":10,
"field2":20,
"msg":
{
"a":1,
"b":2,
"c":3
}
}
]
For reasons, I need to pull the a and b fields from msg and flatten their names:
[
{
"field1":10,
"field2":20,
"msg.a":1,
"msg.b":2,
"msg": # the entire msg structure is now optional; if it falls off that's ok
{
"a":1,
"b":2,
"c":3
},
}, ...
]
How is the miracle accomplished?
>Solution :
This works fine with the example input:
map(. + (.msg | {"msg.a": .a, "msg.b": .b}))
This is more flexible if the actual task involves more keys or keys with longer names:
map(. + (.msg | {a, b} | with_entries(.key |= "msg.\(.)")))
And if you do this for several fields like msg, a function could help shorten the code:
def f(x): . as $in
| reduce path(x) as $p ({};
. + {($p | join(".")): $in | getpath($p)}
);
map(. + f(.msg | .a, .b))