shell處理json字符串

對於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"}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章