如何从包含值的JSON对象中的数组中删除元素 [英] How do I remove elements from array in a JSON object containing a value

查看:63
本文介绍了如何从包含值的JSON对象中的数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意,该帖子被标记为 jq ,我完全不尝试使用javascript.

Please note that this post is tagged jq, I am not trying to do this with javascript at all.

我有一个对象,该对象具有一个数组作为其字段之一.我想从对象数组中删除符合条件的元素,但要保留对象.我环顾四周,我只能发现返回 just 数组的片段,这些数组现在恰好具有较少的项.

I have an object that has an array as one of its fields. I'd like to remove the elements from the object's array that match a criteria, but keep the object around. I've looked around and I've only been able to spot snippets of returning just the array that happens to have less items now.

这是一个例子:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    },
    {
      "id": null,
      "msg": "done"
    }
  ]
}

,我想找回以下信息:

{
  "foo": "bar",
  "events": [
    {
      "id": 1,
      "msg": "starting"
    },
    {
      "id": 2,
      "msg": "working on it"
    }
  ]
}

注意:万一这会影响答案,我真的只对最后一个元素感兴趣.我计划在以下管道阶段中建立一个新对象,例如:

Note: Just in case this will affect the answer I'm really only interested in the last element. I plan to build up a new object in a following pipe stage like:

jq '$answer | {bar:.foo, event: .events[-1].msg}`

我都尝试过

select(.events[].id != null)

del(.events[], select(.id == null)))

没有运气.

推荐答案

我认为您可能正在寻找 jq 过滤器,如下所示.表达式 .events [] |select(.id == null)将键返回到 id 值为null且 del()删除该键/值对的对象./p>

I think you are probably looking for jq filter as below. The expression .events[] | select(.id == null) returns the key to the object where the id value is null and del() deletes that key/value pair.

jq 'del(.events[] | select(.id == null))'

作为旁注,如果您只想按索引删除元素,则可以按以下方式使用.下面的示例从索引2中删除该元素,该数组实际上从0开始.

As a side note, if you just want to delete an element just by index, you could just use as below. The example below deletes the element from index 2, the array actually starts at 0.

jq 'del( .events[2] )'

但是请记住,对于您的原始问题,不建议使用这种方法,因为您不知道键的哪个索引将包含空值.

But remember this way is not recommended for your original problem, since you wouldn't know which index of your key would contain the null value.

这篇关于如何从包含值的JSON对象中的数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆