json - 如何使用 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 工具的方式使用它
解决方案
该path()
功能派上用场:
$ jq -c 'path(.. | select(. == "wetransfer@extensions.thunderbird.net"))' input.json
["addons",0,"id"]
结果路径被解释为“在初始对象的 addons 字段中,第一个数组元素的 id 字段匹配”。您可以将它与getpath()
, setpath()
,delpaths()
等一起使用来获取或操作它所描述的值。
推荐阅读
- javascript - 如何使用电子创建 Outlook 对象 - 新电子邮件?
- c# - 使用 Autofac 在我的组件类 Azure Functions 中注入 ILogger 实例
- php - 如何使用 htaccess 从 url 中隐藏目录名称?
- node.js - 输出显示未定义
- pyspark - 在整行上使用 udf 过滤 Pyspark Dataframe
- javascript - Ag-grid 不垂直向下滚动
- python - requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))
- python - Pyautogui 滚动微调?
- angular6 - 无法创建嵌套的反应表单
- python - 从列表的字典中理解列表