我刚开始使用jq,可以在以下方面得到帮助.
本质上,我试图使用bash脚本“查找并替换”文件中的一个json块。
我有一个名为docs.json的文件,在这里我检索了一组文档条目:
{
"number_of_docs": "1000",
"docs": [{
{
"_id": "000001",
"_rev": "0",
"_content": "abcdefg"
},
{
"_id": "000002",
"_rev": "0",
"_content": "hijklmn",
"_attachments": {
"image1.png": {
"content_type": "image/png"
...
}
}
},
{
"_id": "000003",
"_rev": "0",
"_content": "opqrstuv"
}]
}我试图用存储在一个名为“doc”的变量中的新的json块替换所有具有"_attachments“的文档条目(整个块,而不仅仅是键的值):
{
"_id": "000002_masked",
"_rev": "0",
"_content": "[Document content has been masked for confidentiality.]",
"_attachments": {
"confidential.png": {
"content_type": "image/png"
...
}
}
}对于jq和在bash脚本中运行,我想要做的事情可能吗?
谢谢您的帮助和提示,提前。
发布于 2016-07-19 20:07:08
关键是选择具有_attachments键的文档,然后用|=操作符替换它们。
jq --argjson new "$doc" '(.docs[]| select(has("_attachments"))) |= $new' docs.json--argjson用于将$doc的值作为原始JSON值传递到过滤器中。
发布于 2017-08-28 02:02:28
如果您不能使用--argjson,您可以使用-s slurp选项以及一个过滤器,例如
.[0] as $new
| .[1]
| ( .docs[] | select(has("_attachments")) ) = $new如果以上内容在filter.jq中,则new.json中的新文档和数据包含一个对象,如您在docs.json中所描述的。
jq -M -s -f filter.jq new.json docs.json将产生
{
"number_of_docs": "1000",
"docs": [
{
"_id": "000001",
"_rev": "0",
"_content": "abcdefg"
},
{
"_id": "000002_masked",
"_rev": "0",
"_content": "[Document content has been masked for confidentiality.]",
"_attachments": {
"confidential.png": {
"content_type": "image/png"
}
}
},
{
"_id": "000003",
"_rev": "0",
"_content": "opqrstuv"
}
]
}注意-我没有jq-1.3,所以我只能用jq-1.5验证这一点,但我认为这应该适用于jq-1.3
https://stackoverflow.com/questions/38466960
复制相似问题