update
This commit is contained in:
+12
-2
@@ -1,7 +1,9 @@
|
||||
#!/bin/bash
|
||||
|
||||
# 修改json文件的属性值
|
||||
# 调用方式:modify_json_file "/foo/bar.json" "person.name" "张三"
|
||||
# 案例1:modify_json_file "/foo/bar.json" "person.name" "张三"
|
||||
# 案例2:modify_json_file "/foo/bar.json" "servers" '["a.com", "b.com"]'
|
||||
# 该函数能自动处理不同数据类型,包括数组、对象和数字等。
|
||||
function modify_json_file() {
|
||||
local json_file=$1 # json文件路径
|
||||
local key=$2 # 要修改的key
|
||||
@@ -12,6 +14,14 @@ function modify_json_file() {
|
||||
key=${key:1}
|
||||
fi
|
||||
|
||||
jq ".${key} = \"${value}\"" ${json_file} > ${json_file}.tmp
|
||||
# 检查值是否为有效的 JSON 格式(如数组、对象或数字)。
|
||||
# 如果是,则直接将值传递给 jq,无需引号。
|
||||
if echo "${value}" | jq . >/dev/null 2>&1; then
|
||||
jq ".${key} = ${value}" "${json_file}" > "${json_file}.tmp"
|
||||
else
|
||||
# 否则,将值视为字符串,并添加引号。
|
||||
jq ".${key} = \"${value}\"" "${json_file}" > "${json_file}.tmp"
|
||||
fi
|
||||
|
||||
mv ${json_file}.tmp ${json_file}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user