How to Read Parameters from a JSON File in BASH Script?



How to Read Parameters from a JSON File in BASH Script? | ninjasquad

bash-shellshock How to Read Parameters from a JSON File in BASH Script? bash script BASH Shell JSON Shell Scripts

bash-shellshock

The parameters can be passed as command line to the shell scripts as $1, $2 etc. However, if there are many parameters, passing via command line is not ideal and convenient.

We can utilize the jq command/tool to parse a JSON string. First, lets test if the jq is installed:

1
2
3
4
5
6
7
#!/bin/bash
 
test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi
#!/bin/bash

test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi

Then, we let the $1 passed as the first command line parameter – which points to an external JSON file:

1
2
3
4
5
6
config=$1
 
if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi
config=$1

if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi

Then, we need to store the file content in a shell variable:

And then, we declare a shell function (BASH) to read the parameter in a JSON string:

1
2
3
readJsonConfig() {
        echo $json | jq -r $1
}
readJsonConfig() {
        echo $json | jq -r $1
}

Given the following JSON file:

{
        "data": {
                "x": "Hello, world!"
        }
}

The following prints “Hello, world!”

1
echo $(readJsonConfig ".data.x")
echo $(readJsonConfig ".data.x")

As you can see, we use the single dot “.” to follow the path in JSON. Here is the complete BASH source code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/bin/bash
 
test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi
 
config=$1
 
if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi
 
json=$(cat $config)
 
readJsonConfig() {
        echo $json | jq -r $1
}
 
echo $(readJsonConfig ".data.x")
#!/bin/bash

test_json=$(echo "{ }" | jq)
if [ "$test_json" != "{}" ]; then
        echo "jq not installed"
        exit 1
fi

config=$1

if [ ! -f "$config" ]; then
        echo "config file $config not valid"
        exit 2
fi

json=$(cat $config)

readJsonConfig() {
        echo $json | jq -r $1
}

echo $(readJsonConfig ".data.x")

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading…

413 words
Last Post: Teaching Kids Programming – Introduction to SQL and the SELECT
Next Post: Teaching Kids Programming – Most Common SQL keywords (Select, Update, Insert, Delete)





Source: Internet

Leave a Comment

We are offering free coding tuts

X