json - 用文件内容替换关键字

标签 json bash shell sed jq

我有一个名为 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/

相关文章:

c# - 使用 JsonProperty 将 JSON 绑定(bind)到模型属性

php - 我在哪里放 $this->request->headers ('Content-Type' , 'application/json' );

linux - 如何检索处于可中断 sleep (S+)或其他状态的进程?

regex - 仅当具有给定名称的 Docker 容器不存在时,如何执行 Bash 命令?

c - 实现管道以模仿 Shell

c# - 如何将 json-patch 应用于 .net core 中的纯 json?

c# - 通过 GET 请求将 JSON 参数传递给 MVC Controller

Bash 将 heredoc 输出重定向到/dev/null

linux - 从 sudo-ed 环境启动 bash shell

shell - 在第 34 行出现语法错误 : `<<' unmatched in ksh script