對於shell一般字符串的解析可以使用grep/sed/cut/awk等命令,對於json字符串的解析一般使用jq命令,但是有時需要在shell中構建json字符串,對於這種情況下使用python處理非常方便,下面便在shell中調用python構建json字符串。
#!/bin/bash
str='{
"orig": {
"a1": "1",
"a2": "2",
"a3": "3"
},
"add": {
"b1": "1",
"b2": "2"
}
}'
py_code="
import sys, json
input = sys.stdin.read()
str = input.replace(' ', '')
dict = json.loads(str)
dict_orig = dict.get('orig', {})
dict_add = dict.get('add', {})
dict_orig.update(dict_add)
print(json.dumps(dict_orig))
"
main()
{
value=$(echo ${str}|python -c "${py_code}")
echo "Get value: ${value}"
}
main
運行結果:
[root@master ~]# sh json_string_covert.sh
Get value: {"a1": "1", "a2": "2", "a3": "3", "b1": "1", "b2": "2"}