Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

flattening a json file using jq

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[
{
"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))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading