代码之家  ›  专栏  ›  技术社区  ›  Tony Ennis

使用jq压平json文件

  •  0
  • Tony Ennis  · 技术社区  · 11 月前

    我想压平一个json文件,以满足遗留程序的需要。我更喜欢使用 jq 据我所知,这是我可以使用的。

    我有一个文件,内容如下:

    [
    {
    "field1":10,
    "field2":20,
    "msg":
      {
      "a":1,
      "b":2,
      "c":3
      }
    }
    ]
    

    出于某些原因,我需要从 msg 并将它们的名称压平:

    [
    {
    "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
      },
    }, ...
    ]
    

    奇迹是如何实现的?

    1 回复  |  直到 11 月前
        1
  •  2
  •   oguz ismail FCulig    11 月前

    这与示例输入配合得很好:

    map(. + (.msg | {"msg.a": .a, "msg.b": .b}))
    

    如果实际任务涉及更多的键或名称更长的键,则此操作更灵活:

    map(. + (.msg | {a, b} | with_entries(.key |= "msg.\(.)")))
    

    如果你对几个领域这样做,比如 msg ,一个函数可以帮助缩短代码:

    def f(x): . as $in
    | reduce path(x) as $p ({};
      . + {($p | join(".")): $in | getpath($p)}
    );
    map(. + f(.msg | .a, .b))