假设有一个数组类型域,其成员是一个结构类型,例如:
{
"docs": [
{
"name": "Tom",
"age": 20,
"address": "Tom's address"
},
{
"name": "Jerry",
"age": 30,
"address": "200 Land"
},
{
"name": "Jack",
"age": 30,
"address": "New address"
}
]
}
如果使用遍历数组,拿到每一个struct用来分析呢:
#!/bin/bash
cat test.json | jq '.docs[]' | while read doc; do
echo $doc
done
看起来很合理,运行一下呢:
{
"name": "Tom",
"age": 20,
"address": "Tom's address"
}
{
"name": "Jerry",
"age": 30,
"address": "200 Land"
}
{
"name": "Jack",
"age": 30,
"address": "New address"
}
看不出效果:
$ cat test.json
#!/bin/bash
cat test.json | jq '.docs[]' | while read doc; do
echo "DOC="$doc
done
$ ./test.sh
DOC={
DOC="name": "Tom",
DOC="age": 20,
DOC="address": "Tom's address"
DOC=}
DOC={
DOC="name": "Jerry",
DOC="age": 30,
DOC="address": "200 Land"
DOC=}
DOC={
DOC="name": "Jack",
DOC="age": 30,
DOC="address": "New address"
DOC=}
这下看清楚了,显然是不行的,我们得想办法把一个元素拼成一行才好。
$ cat test.json
#!/bin/bash
cat test.json | jq -c '.docs[]' | while read doc; do
echo "DOC="$doc
done
$ ./test.sh
DOC={"name":"Tom","age":20,"address":"Tom's address"}
DOC={"name":"Jerry","age":30,"address":"200 Land"}
DOC={"name":"Jack","age":30,"address":"New address"}
这是我们的目标,于是在循环里面可以访问struct的成员:
$ cat test.json
#!/bin/bash
cat test.json | jq -c '.docs[]' | while read doc; do
name=$(echo $doc | jq .name)
age=$(echo $doc | jq .age)
address=$(echo $doc | jq .address)
echo name=$name, age=$age, address=$address
done
$ ./test.sh
name="Tom", age=20, address="Tom's address"
name="Jerry", age=30, address="200 Land"
name="Jack", age=30, address="New address"
如果含有特殊符合怎么处理,我们可以先进行base64编码,然后在使用的时候解码:
$ cat test.sh
#!/bin/bash
cat test.json | jq -rc '.docs[] | @base64' | while read doc; do
doc=$(echo $doc | base64 -d)
name=$(echo $doc | jq .name)
age=$(echo $doc | jq .age)
address=$(echo $doc | jq .address)
echo name=$name, age=$age, address=$address
done
$ ./test.sh
name="Tom", age=20, address="Tom's address"
name="Jerry", age=30, address="200 Land"
name="Jack", age=30, address="New address"
网友评论