Skip to content

Instantly share code, notes, and snippets.

@DarkVss
Created September 4, 2023 13:53
Show Gist options
  • Save DarkVss/8ea6934b6e2a9d6c9a02f403f0008f24 to your computer and use it in GitHub Desktop.
Save DarkVss/8ea6934b6e2a9d6c9a02f403f0008f24 to your computer and use it in GitHub Desktop.
Bash simple JSON-parser
#!/bin/bash
function json_extract() {
local key=$1
local json=$2
local string_regex='"([^"\]|\\.)*"'
local number_regex='-?(0|[1-9][0-9]*)(\.[0-9]+)?([eE][+-]?[0-9]+)?'
local value_regex="${string_regex}|${number_regex}|true|false|null"
local pair_regex="\"${key}\"[[:space:]]*:[[:space:]]*(${value_regex})"
if [[ ${json} =~ ${pair_regex} ]]; then
echo $(sed 's/^"\|"$//g' <<<"${BASH_REMATCH[1]}")
else
return 1
fi
}
# use json_extract KEY_WHAT_U_NEED JSON_DOC_STRING
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment