首页 > 解决方案 > 如何使用bash替换json中的文本

问题描述

我正在尝试使用 JSON 文件中的 bash 将qa_test_services替换为test_services,有人可以帮我解决这个问题吗?谢谢

JSON 文件 - variables.json

{
    "variable": {
        "qa_test_services": {
            "default": {
                "prod-test-1": {
                    "position": 0,
                    "service_name": "test-1-service"
                },
                "prod-test-2": {
                    "position": 1,
                    "service_name": "test-2-service"
                }
            }
        }
    }
}

bash - 脚本

test_json="variables.json"
actual_text="qa_test_services"
replace_text="test_services"

SEARCH_LINE=`cat $test_json | grep $actual_text | sed 's/"//g' | sed 's/://g' | sed 's/{//g' | sed -e 's/  */ /g'`
echo $SEARCH_LINE

标签: jsonbash

解决方案


我会避免使用面向行的工具编辑 json 的诱惑。像 xml 一样,它的格式并不总是很好。尝试使用 jq; 这就像 sed 的 json。

jq -f filter.jq variables.json

过滤器.jq

.variable |= with_entries(
    if .key == "qa_test_services" then
        .key = "test_services"
    else
        .
    end)

输出

{
  "variable": {
    "test_services": {
      "default": {
        "prod-test-1": {
          "position": 0,
          "service_name": "test-1-service"
        },
        "prod-test-2": {
          "position": 1,
          "service_name": "test-2-service"
        }
      }
    }
  }
}

使用 bash 变量

jq ".variable |= with_entries(
    if .key == \"$actual_text\" then
        .key = \"$replace_text\"
    else
        .
    end)" $test_json

推荐阅读