我有这样的json字符串:
{
viewer {
login
name
repository(name: "git-point-playground") {
id
descriptionHTML
object(expression: "master:README.md") {
id
... on Blob {
text
}
}
}
}
}
我使用jq编写了一个简单的for循环来提取值,但没有得到所需的结果。
jstring='[{"userQuery":"select name from abc;","user":"abc"},{"userQuery":"select name from xyz;","user":"xyz"},{"userQuery":"select name from ppp;","user":"ppp"}]'
借助此行:for i in `echo $jstring | jq '.[] | [.user, .userQuery]'`; do echo ${i}; done
。我能够提取以下信息:
echo $jstring | jq '.[] | [.user, .userQuery]'
现在,我想要两个变量" user" &安培; "查询"对于每个数组并存储该信息。
例如:对于[" abc","从abc中选择名称;"] - user:abc,query:"从abc"中选择名称并存储它们。
我不确定如何使用jq迭代json并获取单个值并存储它们。
答案 0 :(得分:2)
jq + bash 解决方案:
#!/bin/bash
jstring='[{"userQuery":"select name from abc;","user":"abc"},{"userQuery":"select name from xyz;","user":"xyz"},{"userQuery":"select name from ppp;","user":"ppp"}]'
while IFS=$'\t' read -r user query; do
msg="User: ${user} is running : ${query}"
mail -s "User query" "youremail@gmail.com" <<< "$msg"
done < <(jq '.[] | [.user,.userQuery] | @tsv' <<< "$jstring")
答案 1 :(得分:1)
我认为您的意思是要将它们存储为 shell 变量。有了bash,你可以写:
while read -r user query; do
echo "user->$user"
echo "query->$query"
done < <( jq -r '.[] | "\(.user) \(.userQuery)"' <<< "$jstring" )
user->abc
query->select name from abc;
user->xyz
query->select name from xyz;
user->ppp
query->select name from ppp;
秘密酱是在jq内部的字符串的表达中引用\(.user)
的对象属性
我假设用户名不包含空格。否则,我们必须在该字符串中使用不同的分隔符,并将IFS
与shell read命令一起使用。