从JSON对象中提取2个值,并使用jq和bash在循环中用作变量 [英] extract 2 values from JSON object and use as variables in loop using jq and bash

查看:699
本文介绍了从JSON对象中提取2个值,并使用jq和bash在循环中用作变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是jq的新手.我正在尝试编写一个简单的脚本,该脚本遍历JSON文件,在每个对象中获取两个值,并将它们分配给两个单独的变量,我可以在curl REST调用中使用它们.当我回显$ i时,我将两个值都视为输出,但是如何将值和addr作为单独的变量获取呢?

I am new to jq. I am trying to write a simple script that loops through a JSON file, gets two values within each object and assigns them to two separate variables I can use with a curl REST call. I see both values as output when I echo $i but how can I get value and addr as separate variables?

for i in `cat /Users/egraham/Downloads/test2  | jq .[] | jq ."value,.addr"`; do

推荐答案

如果空格或制表符或其他特殊字符使使用'read -r'产生问题,并且如果您的外壳具有"readarray",则可以使用: /p>

If spaces or tabs or other special characters make using 'read -r' problematic, and if your shell has "readarray", then it could be used:

$ readarray -t v < <(jq -rc '.populator | (.value,.addr)' file.json)

这些值将分别作为$ {v [0]}和$ {v [1]}

The values would then be available as ${v[0]} and ${v[1]}

如果感兴趣的值多于两个,或者值的数量是可变的或事先未知,则此方法特别有用.

This approach is especially useful if there are more than two values of interest, or if the number of values is variable or not known beforehand.

如果您的shell没有readarray,那么您仍然可以使用面向数组的方法,例如遵循以下原则:

If your shell does not have readarray, then you can still use the array-oriented approach, e.g. along the lines of:

i=-1; while read -r a ; do i=$((i+1)); v[$i]="$a" ; done

这篇关于从JSON对象中提取2个值,并使用jq和bash在循环中用作变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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