当前位置:网站首页>Awk processing JSON processing

Awk processing JSON processing

2022-07-07 21:15:00 Chestnut less

 Nested parsing and lists will be a little  bug...  However, it meets the requirements of light use 

#!/bin/bash

json_str='{
  "access_token":"12345678-1234-1234-1234-123456789012",
  "token_type":"bearer",
  "refresh_token":"12345678-1234-1234-1234-12345678901"
}'

get_json_value() {
    awk -v json="$1" -v key="$2" -v defaultValue="$3" 'BEGIN{
        foundKeyCount = 0
        while (length(json) > 0) {
            pos = match(json, "\""key"\"[ \\t]*?:[ \\t]*");
            if (pos == 0) {if (foundKeyCount == 0) {print defaultValue;} exit 0;}
            ++foundKeyCount;
            start = 0; stop = 0; layer = 0;
            for (i = pos + length(key) + 1; i <= length(json); ++i) {
                lastChar = substr(json, i - 1, 1)
                currChar = substr(json, i, 1)
                if (start <= 0) {
                    if (lastChar == ":") {
                        start = currChar == " " ? i + 1: i;
                        if (currChar == "{" || currChar == "[") {
                            layer = 1;
                        }
                    }
                } else {
                    if (currChar == "{" || currChar == "[") {
                        ++layer;
                    }
                    if (currChar == "}" || currChar == "]") {
                        --layer;
                    }
                    if ((currChar == "," || currChar == "}" || currChar == "]") && layer <= 0) {
                        stop = currChar == "," ? i : i + 1 + layer;
                        break;
                    }
                }
            }
            if (start <= 0 || stop <= 0 || start > length(json) || stop > length(json) || start >= stop) {
                if (foundKeyCount == 0) {print defaultValue;} exit 0;
            } else {
                print substr(json, start, stop - start);
            }
            json = substr(json, stop + 1, length(json) - stop)
        }
    }'
}

echo $(get_json_value "${json_str}" "refresh_token")
原网站

版权声明
本文为[Chestnut less]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/188/202207071837353747.html