问题
I try to use jq to parse a json file and use it in a bash script, but i'm having some difficulties. The json
[
{"annonce_id":"123","photos":["url_01"],"titre_slug":"slug1"},
{"annonce_id":"456","photos":["url_11","url_12"],"titre_slug":"slug2"},
{"annonce_id":"7890","photos":["url_31"],"titre_slug":"slug3"},
{"annonce_id":"1234","photos":["url_41"],"titre_slug":"slug4"},
{"annonce_id":"5678","photos":["url_51"],"titre_slug":"slug5"},
{"annonce_id":"90123","photos":["url_61"],"titre_slug":"slug6"}
]
The goal : For each line, retrieve annonce_id, titre_slug and photos in bash variables. Photos should be in an array, since it can contain 1 or more elements.
If i do a
jq -r '.[] | .annonce_id, .titre_slug, .photos'
on this data, i display the info, but i'd like to have it in bash variables (preferably named after the json fields), to use annonce_id and titre_slug, and iterate over photos.
Thanks
回答1:
There are many possible solutions in bash. Here's one that does NOT require mapfile
(aka readarray
):
while read -r annonce
do
read -r titre
IFS=$'\t' read -r -a photos
echo annonce="$annonce"
echo titre="$titre"
echo number of photos is ${#photos[@]}
done < <(jq -r '.[] | .annonce_id, .titre_slug, (.photos | @tsv)' input.json)
回答2:
#!/bin/bash
json_file="/home/pruebas/file.json"
while read line
do
if [ $(echo $line|grep annonce|wc -l) -gt 0 ]
then
var_annonce_id=$(echo $line |grep annonce |awk 'BEGIN {FS="\""}{print $4}')
var_titre_slug=$(echo $line |grep annonce |awk 'BEGIN {FS="\]"}{print $2}' | awk 'BEGIN {FS="\""}{print $4}')
var_photo_array=$(echo $line |grep annonce |awk 'BEGIN {FS="\["}{print $2}' |awk 'BEGIN {FS="\]"}{print $1}' |tr -d "\"" | sed s/"\,"/" "/g )
echo "Annonce_id=$var_annonce_id"
echo "Titre_slug=$var_titre_slug"
echo "Photo Array=$var_photo_array"
fi
done < $json_file
来源:https://stackoverflow.com/questions/48324463/bash-and-jq-nested-loops-on-json