I'm trying to fetch values of a nested key from json file in bash using python one-liner. Below given is my json file content.
{
"conditional_ks": {
"saturday":["reportdata_by_type"],
"sunday":["rt_report","metadata"]
}
}
I want all values ["reportdata_by_type","rt_report","metadata"] as a list. I did like,
[root@testnode1 repair]# python -c "import json; print json.load(open('repair.json','r'))[\"conditional_ks\"].values()"
output: [[u'rt_report', u'metadata'], [u'reportdata_by_type']]
but i need output like ['rt_report','metadata','reportdata_by_type']
Note: repair.json is json file name.
one option is using conditional_ks.*[]
which supposed to give output like:
["reportdata_by_type", "rt_report", "metadata" ]
But in bash i'm unable to use it.
Can anyone has solution to this, please help.
python -c "import json; import itertools; print(list(itertools.chain(*(json.load(open(\"repair.json\", 'r'))[\"conditional_ks\"].values()))))"
I have tested the code in my computer and it works properly. May this be helpful.
As always, jq is the tool of choice for working with json from a command line:
$ jq '.conditional_ks.saturday + .conditional_ks.sunday' repair.json
[
"reportdata_by_type",
"rt_report",
"metadata"
]
Edit: If your real data has more fields than just those two specific ones and you want to concatenate all the values of conditional_ks
fields, then:
$ jq '[ .conditional_ks[] ] | flatten' repair.json
will do the trick.
like below i solved the problem :
python -c "import json; print reduce(lambda x,y: x+y,json.load(open('repair.json','r'))[\"conditional_ks\"].values())"
output : [u'rt_report', u'metadata', u'reportdata_by_type']
Try follow Script. $1 is your json file, like
./MyScript.sh 'PathToYourJsonFile'
MyScript.sh:
#!/bin/bash
content=$(cat "$1");
string="";
echo "[";
while read line; do
split=$(echo $line | sed -e 's/.*\[\(.*\)\]/\1/' | sed -s 's/",/" /g');
for i in $split; do
echo "$i,"
done
done< <(echo -n "$content" | grep "\:\[");
echo "]";
Result:
[
"reportdata_by_type",
"rt_report",
"metadata",
]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.