Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read JSON file & parse to get element values in shell script

Tags:

json

shell

I have a json file names test.json with the below content.

{
        "run_list": ["recipe[cookbook-ics-op::setup_server]"],
    "props": {
        "install_home": "/test/inst1",
            "tmp_dir": "/test/inst1/tmp",
        "user": "tuser
                 }
}

I want to read this file into a variable in shell script & then extract the values of install_home,user & tmp_dir using expr. Can someone help, please?

props=cat test.json

works to get the json file into a variable. Now how can I extract the values using expr. Any help would be greatly appreciated.

like image 547
Newbie Avatar asked Jan 08 '23 05:01

Newbie


2 Answers

Install jq

yum -y install epel-release
yum -y install jq

Get the values in the following way

install_home=$(cat test.json  | jq -r '.props.install_home')
tmp_dir=$(cat test.json  | jq -r '.props.tmp_dir')
user=$(cat test.json  | jq -r '.props.user')
like image 90
Sahit Avatar answered Jan 09 '23 18:01

Sahit


For a pure bash solution I suggest this:
github.com/dominictarr/JSON.sh
It could be used like this:

./json.sh -l -p < example.json  

print output like:

["name"]        "JSON.sh"
["version"]     "0.2.1"
["description"] "JSON parser written in bash"
["homepage"]    "http://github.com/dominictarr/JSON.sh"
["repository","type"]   "git"
["repository","url"]    "https://github.com/dominictarr/JSON.sh.git"
["bin","JSON.sh"]       "./JSON.sh"
["author"]      "Dominic Tarr <[email protected]> (http://bit.ly/dominictarr)"
["scripts","test"]      "./all-tests.sh"

From here is pretty trivial achive what you are looking for

like image 23
Thomas8 Avatar answered Jan 09 '23 18:01

Thomas8