This repository has been archived by the owner on May 2, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjson-parser.func.sh
111 lines (78 loc) · 1.7 KB
/
json-parser.func.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#! /usr/bin/env bash
#
# Retrieve the content of a JSON file and the value of a specific key.
##
##
# Check if the path to the file is a JSON file.
#
# Arguments:
# json file path
# Outputs:
# boolean
##
is_json_file () {
local -r json_file_path="${1}"
if [[ -f "${json_file_path}" ]] && [[ "${json_file_path}" == *'.json' ]]; then
printf 'true'
else
printf 'false'
fi
}
##
# Check if the key name is in the content.
#
# Arguments:
# content
# key name
# Outputs:
# boolean
##
has_key_name () {
local -r content="${1}"
local -r key_name="${2}"
if [[ "${content}" == *"${key_name}"* ]]; then
printf 'true'
else
printf 'false'
fi
}
##
# Retrieve the content of the JSON file.
#
# Arguments:
# json file path
# Outputs:
# json file content or empty string
##
get_file_content () {
local -r json_file_path="${1}"
local -r is_json_file="$(is_json_file "${json_file_path}")"
if "${is_json_file}"; then
remove_white_space "$(<"${json_file_path}")"
else
printf ''
fi
}
##
# Retrieve the value of the key.
#
# Arguments:
# file content
# key name
# first delimiter
# last delimiter
# Outputs:
# key value or empty string
##
get_key_value () {
local -r file_content="${1}"
local -r key_name="${2}"
local -r first_delimiter="${3}"
local -r last_delimiter="${4}"
local -r has_key_name="$(has_key_name "${file_content}" "${key_name}")"
if [[ -n "${file_content}" ]] && "${has_key_name}"; then
printf "%s" "${file_content}" | sed "s/^.*\"${key_name}\": ${first_delimiter}//; s/${last_delimiter}.*$//"
else
printf ''
fi
}