1
我有,我需要解析引用JSON在JSON的情況下的列表。 我知道哪個可選屬性將包含帶引號的JSON,哪些不是。 因此,我想檢查屬性鍵是否在可能的鍵列表中。我已經有以下幾種:JQ:如果測試的關鍵是在預定義項
# attributes "a" and "b" contain quoted JSON
echo '{"a":"{\"x\":1}","y":2}' |
jq -c '
def is_json($o): ["a","b"] | (map(select(. == $o)) | length) > 0;
with_entries(if is_json(.key) then .value = (.value|fromjson) else . end)
'
這已經產生了所需的輸出:{"a":{"x":1},"y":2}
。然而,屬性名的檢查看起來笨拙,因爲jq
提供了內置的功能很多,如has
,in
,contains
,inside
等
問:有沒有檢查如果一個更好的辦法屬性鍵在給定列表中?
編輯:這是當前的解決方案,基於峯值的答案。
#!/bin/bash
to_array_string() { echo "$*" | awk -v OFS='","' 'NF > 0 {$1=$1; print "\""$0"\""}'; }
to_json_array_string() { echo "["`to_array_string "[email protected]"`"]"; }
parse_json_jq() { jq -c "
reduce keys[] as \$key
(.; if any((`to_array_string "[email protected]"`); . == \$key) and .[\$key] != null then .[\$key] |= fromjson else . end)
";}
Thx for this solution。我只需要添加另一個'null'檢查來使其工作(請參閱編輯問題)。 – Juve