Bash Jq解析json字符串

时间:2016-07-20 14:47:04

标签: json linux bash ubuntu jq

我要调用一个文件并以这种方式传递json作为参数 (假设我的文件名为test.sh),从bash我需要做这样的事情:

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

以及test.sh的内容如下

#!/bin/bash

#read the json
system_user="$1"

printf "$system_user"

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

printf "$accounts"

for account in "${accounts[@]}"
do
  printf "\n\n$account\n\n"
done 

输出 - &gt; printf“$ system_user”是

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

但输出 - &gt; printf“$ accounts”就是这样的

[
[
{
“用户名”:
“USER1”
等等每个令牌的一个对象:-(

依此类推,但我期待的是三个对象的数组(就像你可以在jqplay.org上测试一样)

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

通过这种方式,我可以在$ {accounts [@]}

上制作一个foreach

我做错了什么? 谢谢

2 个答案:

答案 0 :(得分:2)

使用-c选项,您可以在一行上打印每个JSON对象,从而更容易填充所需的数组。

$ 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: %s\n" "${arr[@]}"
Object: {"username":"user1","password":"pwd1","group":"usergroup1"}
Object: {"username":"user2","password":"pwd2","group":"usergroup2"}
Object: {"username":"user3","password":"pwd3","group":"usergroup3"}

答案 1 :(得分:1)

您正在交换bash数组和JSON数组。当您创建accounts数组时,bash会按每个空格分割元素。这就是为什么你没有得到你期望的。您可以尝试以下方法:

declare -A accounts

while IFS="=" read -r key value
do
    accounts[$key]="$value"
done < <(jq -r "to_entries|map(\"\(.key)=\(.value)\")|.[]" <<< $system_user)

for account in "${accounts[@]}"
do
    printf "$account\n"
done

(从这里偷来:https://stackoverflow.com/a/26717401/328977

获取以下输出:

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