Monday, December 31, 2018

如何在 bash 下解析 JSON 資料

以下是其中的三個方案

1. 使用 python
echo "$DATA" | python -c "import json, sys; obj=json.load(sys.stdin); print(obj['name'])";

# echo '{"test":"123","test2":[{"test21":"456"}]}' | python -c "import json, sys; obj=json.load(sys.stdin); print(obj['test'])"
123

# echo '{"test":"123","test2":[{"test21":"456"}]}' | python -c "import json, sys; obj=json.load(sys.stdin); print(obj['test2'])"
[{'test21': '456'}]

2. 使用 awk sed tr
echo "$DATA" | sed "s/[{}]//g" | tr '[]' ' ' | sed 's/^ //' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'

# echo '{"test":"123","test2":[{"test21":"456"}]}' | sed "s/[{}]//g" | tr '[]' ' ' | sed 's/^ //' | awk -v k="text" '{n=split($0,a,","); for (i=1; i<=n; i++) print a[i]}'
"test":"123"

"test2": "test21":"456" 

3. 使用 jq
# echo '{"test":"123","test2":[{"test21":"456"}]}' | jq -r '.test'

123

Ref:
https://stackoverflow.com/questions/1955505/parsing-json-with-unix-tools

No comments: