简体   繁体   中英

Flatten nested JSON with jq

I'm trying to flatten some nested JSON with jq. My first attempt was by looping over the JSON in bash with base64 as per this article . It turned out to perform very slowly, so I'm trying to figure out an alternative with just jq.

I have some JSON like this:

[
  {
    "id":117739,
    "officers": "[{\"name\":\"Alice\"},{\"name\":\"Bob\"}]"
  },
  {
    "id":117740,
    "officers":"[{\"name\":\"Charlie\"}]"
  }
]

The officers field holds a string which is JSON too. I'd like to reduce this to:

[
  { "id":117739, "name":"Alice" },
  { "id":117739, "name":"Bob" },
  { "id":117740, "name":"Charlie" }
]

Well the data you're attempting to flatten is itself JSON so you have to parse it using fromjson . Once parsed, you could then generate the new objects.

map({id} + (.officers | fromjson[]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM