Skip to content
Advertisement

Bash Jq parse json string

I’ve to call a file and pass a json as parameters in this way (suppose that my file is called test.sh), from bash I need to do something like this:

./test.sh "[{"username":"user1","password":"pwd1","group":"usergroup1"},{"username":"user2","password":"pwd2","group":"usergroup2"},{"username":"user3","password":"pwd3","group":"usergroup3"}]"

and the content of test.sh is the following

#!/bin/bash

#read the json
system_user="$1"

printf "$system_user"

accounts=($(jq -s ".[]" <<< $system_user))

printf "$accounts"

for account in "${accounts[@]}"
do
  printf "nn$accountnn"
done 

the output of -> printf “$system_user” is

[{"username":"user1","password":"pwd1","group":"usergroup1"},{"username":"user2","password":"pwd2","group":"usergroup2"},{"username":"user3","password":"pwd3","group":"usergroup3"}]

but the output of -> printf “$accounts” is something like this

[
[
{
“username”:
“user1”
etc. etc. one object for each token 🙁

and so on, but what I was expecting is an array of three object (like you can test on jqplay.org)

 {
   "username": "user1",
   "password": "pwd1",
   "group": "usergroup1"
 }
 {
   "username": "user2",
   "password": "pwd2",
   "group": "usergroup2"
 }
 {
   "username": "user3",
   "password": "pwd3",
   "group": "usergroup3"
 }

In this way I can make a foreach on ${accounts[@]}

What I’m doing wrong? Thank you

Advertisement

Answer

With the -c option, you can print each JSON object on a single line, making it easier to populate the array you want.

$ readarray -t arr < <(jq -c '.[]' <<< "[{"username":"user1","password":"pwd1","group":"usergroup1"},{"username":"user2","password":"pwd2","group":"usergroup2"},{"username":"user3","password":"pwd3","group":"usergroup3"}]") 
$ printf "Object: %sn" "${arr[@]}"
Object: {"username":"user1","password":"pwd1","group":"usergroup1"}
Object: {"username":"user2","password":"pwd2","group":"usergroup2"}
Object: {"username":"user3","password":"pwd3","group":"usergroup3"}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement