首页 > 解决方案 > 如何使用 Bash 在 json 文件中查找内容

问题描述

我想在 JSON 文件中搜索某个键或值,并将其打印在找到它的位置。

例如,当使用jq打印出我的 Firefox 的 extensions.json 时,我会得到类似这样的信息(在此处使用“...”来跳过较长的部分):

{
  "schemaVersion": 31,
  "addons": [
    {
      "id": "wetransfer@extensions.thunderbird.net",
      "syncGUID": "{e6369308-1efc-40fd-aa5f-38da7b20df9b}",
      "version": "2.0.0",
      ...
    },
    {
      ...
    }
  ]
}

假设我想搜索“wetransfer@extensions.thunderbird.net”,并希望有一个输出显示它在哪里找到,如下所示:

{ "addons": [ {"id": "wetransfer@extensions.thunderbird.net"} ] }

有没有办法使用jq或使用其他一些 json 工具来获得它?

我还尝试简单地列出该id文件中的各种 s,并希望我能用 得到它jq '.id',但那只是返回null,因为它显然需要完整路径。

换句话说,我正在寻找一个命令行 json 解析器,我可以以类似于 Xpath 工具的方式使用它

标签: jsonjq

解决方案


path()功能派上用场:

$ jq -c 'path(.. | select(. == "wetransfer@extensions.thunderbird.net"))' input.json
["addons",0,"id"]

结果路径被解释为“在初始对象的 addons 字段中,第一个数组元素的 id 字段匹配”。您可以将它与getpath(), setpath(),delpaths()等一起使用来获取或操作它所描述的值。


推荐阅读