如何从保留文件结构的JSON文件中删除对象

时间:2018-07-09 15:19:14

标签: jq

我有一个具有以下结构的JSON文件:

{
  "data": [
    {
       "subId": "201805111305QIN0A",
       "checkId": "201805111305QIN0A-CPIFK5ZG"
    },
    {
       "subId": "201805111305QIN0A",
       "checkId": "201805111305QIN0A-F7HGMZUV"
    },
    {
       "subId": "201805111305QIN0A",
       "checkId": "201805111305QIN0A-TQCYEITA"
    },
    {
       "subId": "201805111323U8B1D",
       "checkId": "201805111323U8B1D-HO648V2L"
    }
  ]
}

我想做的是删除checkId =“ 201805111305QIN0A-TQCYEITA ”的对象,并使我的文件看起来像这样:

{
  "data": [
    {
       "subId": "201805111305QIN0A",
       "checkId": "201805111305QIN0A-CPIFK5ZG"
    },
    {
       "subId": "201805111305QIN0A",
       "checkId": "201805111305QIN0A-F7HGMZUV"
    },
    {
       "subId": "201805111323U8B1D",
       "checkId": "201805111323U8B1D-HO648V2L"
    }
  ]
}

为此,我使用以下命令行:

jq -r '.data[] | del(select (.checkId=="201805111305QIN0A-TQCYEITA")) | select (.!=null)' /var/data-disable.js

我能够删除所需的对象,但是 jq命令的输出不会保留我的JSON文件的结构,它看起来像这样:

{
  "subId": "201805111305QIN0A",
  "checkId": "201805111305QIN0A-CPIFK5ZG"
}
{
  "subId": "201805111305QIN0A",
  "checkId": "201805111305QIN0A-F7HGMZUV"
}
{
  "subId": "201805111323U8B1D",
  "checkId": "201805111323U8B1D-HO648V2L"
}

1 个答案:

答案 0 :(得分:2)

您可以使用del来代替map(select(..)),但不包括需要的部分。

jq '.data |= map(select(.checkId != "201805111305QIN0A-TQCYEITA"))'

或使用实际的del命令,执行上述相反的操作

jq 'del(.data[] | select(.checkId == "201805111305QIN0A-TQCYEITA"))'