JSON上的Bash和jq嵌套循环 [英] Bash and jq nested loops on json

查看:76
本文介绍了JSON上的Bash和jq嵌套循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用jq解析json文件并在bash脚本中使用它,但是我遇到了一些困难. json

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"}
]

目标: 对于每一行,在bash变量中检索annonce_id,titre_slug和照片.照片应位于一个数组中,因为它可以包含1个或多个元素.

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.

如果我这样做

jq -r '.[] | .annonce_id, .titre_slug, .photos'

在此数据上,我显示信息,但我希望将其包含在bash变量(最好以json字段命名)中,以使用annonce_id和titre_slug并遍历照片.

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.

谢谢

推荐答案

bash中有许多可能的解决方案.这是不需要mapfile(又名readarray)的

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)

这篇关于JSON上的Bash和jq嵌套循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆