【问题标题】:JQ delete property based other property valueJQ删除基于其他属性值的属性
【发布时间】:2015-12-07 20:34:21
【问题描述】:

我正在尝试编写一个 JQ 过滤器,允许我根据对象的其他值选择性地过滤对象属性。

例如,给定以下输入

{
"object1": {
"Type": "Type1",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
 }
},
"object2": {
"Type": "Type2",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
  }
 }
}

我想构建一个过滤器,它基于对象类型,比如“Type2”,删除或清除该对象的属性,比如 Property2。 结果输出将是:

{
"object1": {
"Type": "Type1",
"Properties": {
  "Property1": "blablabla",
  "Property2": [
    {
      "Key": "Name",
      "Value": "xxx"
    },
    {
      "Key": "Surname",
      "Value": "yyy"
    }
  ],
  "Property3": "xxx"
 }
},
"object2": {
"Type": "Type2",
"Properties": {
  "Property1": "blablabla",
  "Property3": "xxx"
  }
 }
}

非常感谢任何帮助。提前致谢。

【问题讨论】:

    标签: json jq


    【解决方案1】:

    很简单。找到要更新的对象,然后更新它们。

    查看你的根对象的值,根据你的条件过滤它们,更新Properties属性删除你想要的属性。

    (.[] | select(.Type == "Type2")).Properties |= del(.Property2)
    

    在对象上使用.[] 会产生对象的所有属性值。另外值得一提的是,当你使用赋值更新一个值时,表达式的结果只是返回输入(换句话说,它不会改变上下文)。

    【讨论】:

    • 谢谢。这似乎适用于完全匹配。这也适用于正则表达式匹配吗?我正在尝试:.["Resources"]|(.[] | select(.Type | match("type2";"i")?)).Properties |= del(.Property2) 但是这似乎不起作用。
    • 在这种情况下,您可能想使用test,但在此处使用正则表达式过滤器时似乎存在优先级问题。 Invalid path expression near attempt to access element "Properties"... 似乎只有在尝试进行更新/重新分配时才会这样做。对我来说似乎是解析器中的一个错误。
    【解决方案2】:

    直接的方法:

    .[] |= (if .Type == "Type2" then delpaths([["Properties", "Property2"]]) else . end)
    

    【讨论】:

    • 您能否详细说明如何解决问题?
    猜你喜欢
    • 1970-01-01
    • 2017-05-03
    • 2019-09-02
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 1970-01-01
    • 2013-02-27
    • 1970-01-01
    相关资源
    最近更新 更多