'How to read json file and store value to some variable in shell script
{"status":
{"reqStatus":"SUCCESS",
"credentials":"R3DMPF8VIAKG6xLa5vOlp7kqmqE.*AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx*****..*",
"msgs":[{"msgCode":"ECMSE103",
"msgText":"User %A1% was authenticated successfully.",
"msgValues":["Tnt_PDU-CD_N53-vPOD4_EO1"]}]
}
}
I have this json file in my directory and I just want to read this json file and have credentials, I just want to store this key value in variable while running shell script code.
Solution 1:[1]
CREDENTIALS=$(awk -F\" '/credentials/ {print $4}' file.json)
Solution 2:[2]
Use FS, OFS and NF to do all the hard-work, since only matching row will have NF = 3 while other non-empty rows will either be 1 or 2 :
input :
{"status":
{"reqStatus":"SUCCESS",
"credentials":"R3DMPF8VIAKG6xLa5vOlp7kqmqE.*AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx*****..*",
"msgs":[{"msgCode":"ECMSE103",
"msgText":"User %A1% was authenticated successfully.",
"msgValues":["Tnt_PDU-CD_N53-vPOD4_EO1"]}]
}
}
command :
mawk 'NF*=2<NF' FS='^.*["]credentials["][ \t]*[:][ \t]*["]|["].*$' OFS=
output :
R3DMPF8VIAKG6xLa5vOlp7kqmqE.*AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx*****..*
Solution 3:[3]
With jq + read and process substitution or command substitution
read var < <(jq '.status.credentials' file.json);
# or
var=$(jq '.status.credentials' file.json);
# output
echo $var
"R3DMPF8VIAKG6xLa5vOlp7kqmqE.*AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx*****..*"
Solution 4:[4]
First, I recommend you format your JSON using a JSON formatter like https://jsonformatter.curiousconcept.com.
Now, let's consider the file test.json which contains your JSON data.
??$ cat test.json
{
"status":{
"reqStatus":"SUCCESS",
"credentials":"R3DMPF8VIAKG6xLa5vOlp7kqmqE.AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx**..*",
"msgs":[
{
"msgCode":"ECMSE103",
"msgText":"User %A1% was authenticated successfully.",
"msgValues":[
"Tnt_PDU-CD_N53-vPOD4_EO1"
]
}
]
}
}
To parse this JSON using bash, we can use the tool jq, which you can install by running, for example in Ubuntu:
sudo apt-get install jq
Once the tools is available, you can run the following to get the Credentials field:
CREDENTIALS=$(cat test.json | jq -r ".status.credentials")
To validate so, run:
??$ echo $CREDENTIALS
R3DMPF8VIAKG6xLa5vOlp7kqmqE.AAJTSQACMDIAAlNLABxXVVhKZkJhMmVOL1ZJQWhRUTBYTGY1V2w2TjA9AAR0eXBlAANDVFMAAlMx**..*
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ufopilot |
| Solution 2 | RARE Kpop Manifesto |
| Solution 3 | Shakiba Moshiri |
| Solution 4 |
