【问题标题】:How to reconstruct single object after its deconstruction in jq如何在jq中解构后重建单个对象
【发布时间】:2019-05-13 08:51:15
【问题描述】:

我收到一个相当大的 json 文件,其中包含许多仅出于历史原因而不再使用的属性。为了简化这个文件,我使用了jq,用to_entries 解构了json,但现在我不知道如何用剩余的子对象重建我的对象。

这是一个例子:

输入

{
  "empty1": [],
  "empty2": [],
  "full1": "test",
  "full2": { "a": 1, "b": 2 }
}

当前过滤器:

to_entries[] | select((.value | length) > 0) | { (.key) : .value }

电流输出

{"full1":"test"}
{"full2":{"a":1,"b":2}}

想要的输出

{
  "full1": "test",
  "full2": {
    "a": 1,
    "b": 2
  }
}

【问题讨论】:

  • 你能显示你正在使用的完整命令吗?

标签: json object jq


【解决方案1】:

使用with_entries() 更短,你可以这样做

jq 'with_entries(select((.value | length) > 0))' json

对于您的问题,from_entriesto_entries 进行相反的转换。并且使用with_entries(foo)to_entries | map(foo) | from_entries 语法的简写。

【讨论】:

  • 我不知道为什么,但由于某种原因,这在 jqplay.org 上不起作用(而 to_entries | map( select((.value | length) > 0) ) | from_entries 起作用)。但是,当我在本地尝试此操作时,它确实有效。谢谢。
猜你喜欢
  • 1970-01-01
  • 2023-01-10
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多