bash 在运行时替换 json 中的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35868649/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 14:21:04  来源:igfitidea点击:

Replace value in json during run time

bash

提问by Sandeep Sharma

I am trying to replace value on run time in json i.e.

我正在尝试在 json 中替换运行时的值

Old

老的

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "myimage",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}

New should be

新的应该是

{
  "containerDefinitions": [{
    "name": "containername",
    "image": "new image",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}
  • Old value: - "image": "myimage"
  • New Value: - "image": "new image"
  • 旧值:-“图像”:“我的图像”
  • 新值:-“图像”:“新图像”

I want to do in bash. Is there any best way to do? Can we do through jq?

我想在 bash 中做。有什么最好的办法吗?可以通过jq吗?

回答by 7171u

You can use jq for this:

您可以为此使用 jq:

jq '.containerDefinitions[].image="new image"' old.son

回答by Sandeep Sharma

You should really use a tool or library that understands JSON. But if your input looks as above, you can use sed:

您真的应该使用理解 JSON 的工具或库。但是,如果您的输入看起来如上,则可以使用sed

$ sed -i '/"image": "myimage"/s/"myimage"/"new image"/' input.json

回答by cb0

This is basically what user suggested, inside a minimalist script! This uses no external programs but depends on bash!

这基本上是用户建议的,在极简脚本中!这不使用外部程序,而是依赖于 bash!

Your new json will be stored in the newStrvariable.

您的新 json 将存储在newStr变量中。

#!/bin/bash

str='
{
  "containerDefinitions": [{
    "name": "containername",
    "image": "myimage",
    "memory": 512,
    "cpu": 1,
    "essential": true,
    "portMappings": [{
      "hostPort": 80,
      "containerPort": 80,
      "protocol": "tcp"
    }]
  }],
  "volumes": [],
  "family": "containername"
}'

replaceValue='"myimage"'
replaceWith='"new image"'
newStr=${str//$replaceValue/$replaceWith}
echo $newStr

Output:

输出:

{ "containerDefinitions": [{ "name": "containername", "image": "new image", "memory": 512, "cpu": 1, "essential": true, "portMappings": [{ "hostPort": 80, "containerPort": 80, "protocol": "tcp" }] }], "volumes": [], "family": "containername" }

{ "containerDefinitions": [{ "name": "containername", "image": "new image", "memory": 512, "cpu": 1, "essential": true, "portMappings": [{ "hostPort ": 80, "containerPort": 80, "protocol": "tcp" }] }], "volumes": [], "family": "containername" }

回答by Mat

Something like this should works for you:

像这样的事情应该适合你:

oldValue='"image": "myimage"'
newValue=${oldValue//myimage/newImage}
echo newValue

In oldValueshould be your json.

oldValue应该是你的json。

回答by Peter Kahn

If python is reliably present, then you can use embedded python like so:

如果python可靠存在,那么您可以像这样使用嵌入式python:

  • setup multiline string
  • execute and fail on error

    #!/usr/bin/evn bash
    # python as multi line string
    
    read -r -d '' PYSCRIPT << ENDPY
    import json
    import os
    jsonfile = 'daemon.json'
    data = {}
    if os.path.exists(jsonfile):
        data = json.load(open(jsonfile))
    data["booleanVar"] = True
    data["stringVar"] = "foo"
    with open(jsonfile, 'w') as fp:
        json.dump(data, fp)
    ENDPY
    
    # execute python and fail on error
    
    echo "$PYSCRIPT" |python - || exit 1
    
  • 设置多行字符串
  • 执行并出错失败

    #!/usr/bin/evn bash
    # python as multi line string
    
    read -r -d '' PYSCRIPT << ENDPY
    import json
    import os
    jsonfile = 'daemon.json'
    data = {}
    if os.path.exists(jsonfile):
        data = json.load(open(jsonfile))
    data["booleanVar"] = True
    data["stringVar"] = "foo"
    with open(jsonfile, 'w') as fp:
        json.dump(data, fp)
    ENDPY
    
    # execute python and fail on error
    
    echo "$PYSCRIPT" |python - || exit 1
    

回答by pkaramol

Given that linuxdoes not by itself allow redirection to the same file, you can use the spongeutility from moreutilspackage

鉴于它linux本身不允许重定向到同一文件,您可以使用包中的sponge实用moreutils程序

- apt update && apt install -y moreutils
- jq '.json_label="json_value"' file.json | sponge file.json

This will truly allow in line replacement;

这将真正允许在线更换;