我有一个名为 template.json 的模板化 json 文件,如下所示:
{
"subject": "Some subject line",
"content": $CONTENT,
}
我有另一个名为 sample.json 的文件,其 json 内容如下:
{
"status": "ACTIVE",
"id": 217,
"type": "TEXT",
"name": "string",
"subject": "string",
"url": "contenttemplates/217",
"content": {
"text": "hello ${user_name}",
"variables": [{
"key": "${user_name}",
"value": null
}]
},
"content_footer": null,
"audit": {
"creator": "1000",
"timestamp": 1548613800000,
"product": "2",
"channel": "10",
"party": null,
"event": {
"type": null,
"type_id": "0",
"txn_id": "0"
},
"client_key": "pk6781gsfr5"
}
我想将 template.json 中的 $CONTENT
替换为 content.json 文件中标签“content”下的内容。我尝试使用以下 sed 命令:
sed -i 's/$CONTENT/'$(jq -c '.content' sample.json)'/' template.json
我遇到以下错误:
sed: -e expression #1, char 15: unterminated `s' command
有人可以帮我获得正确的 sed 命令(或任何其他替代命令)吗?
最佳答案
jq Cookbook 有一节介绍如何将 jq 与模板一起使用:https://github.com/stedolan/jq/wiki/Cookbook#using-jq-as-a-template-engine
在目前的情况下,第一种技术(“使用 jq 变量作为模板变量”)匹配已经定义的模板文件(悬空逗号除外),因此您可以编写:
jq -n --arg CONTENT "$(jq -c .content sample.json)" '
{"subject": "Some subject line", "content": $CONTENT}'
或使用格式:
jq -n --arg CONTENT "$(jq -c .content sample.json)" -f template.jq
(我只对包含 JSON 或 JSON 流的文件使用 .json 后缀。)
关于json - 用文件内容替换关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54402890/