使用jq和带引号的值处理json数组 [英] Processing json array with jq and quoted values

查看:280
本文介绍了使用jq和带引号的值处理json数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个对json对象数组进行一些处理的脚本.源json的简化版本如下所示.注意第二个对象中的转义双引号.

I'm attempting to write a script that does some processing on an array of json objects. A simplified version of the source json looks like this. Note the escaped double quotes in the second object.

[
  {
    "id": "1a-2b",
    "name": "my job name",
    "description": "my job description"
  },
  {
    "id": "3c-4d",
    "name": "my \"quoted\" job name",
    "description": "my \"quoted\" job description"
  }
]

我的脚本当前尝试使用在搜索中其他地方找到的"while read"惯用语来遍历源代码.

My script currently attempts to iterate through the source using a 'while read' idiom I found elsewhere in my searches that looks like this.

while read job; do

  # fetch individual values into variables
  jobname=`echo $job | jq -r '.name'`

  # do processing on the individual values
  echo $jobname

done < <(cat jobs | jq -c '.[]')

问题似乎是转义的引号在紧凑型输出中以及随后的$ job变量中不转义.因此,当我在循环内使用jq重新处理单个对象时,在每个带有引号值的对象上都会出现jq解析错误.

The problem seems to be that the escaped quotes get unescaped in the compact output and subsequently the $job variable. So when I reprocess the individual object with jq inside the loop, I get a jq parse error on each object that has quoted values.

我目前正在使用jq 1.4,并且一直在尝试tojson/fromjson/@ sh/tostring的各种组合,但尚未找到正确的组合.我不反对迁移到jq 1.5,如果它具有使它变得更容易的功能.如果有一种更聪明的方式来做我想做的事情,我也不会嫁给边读边"的习惯用法.

I'm currently using jq 1.4 and I've been trying various combinations of tojson/fromjson/@sh/tostring, but haven't found the right combination yet. I'm not opposed to moving to jq 1.5 if it has a feature that will make this easier. I'm also not married to the 'while read' idiom if there is a smarter way to do what I'm trying to do.

推荐答案

代替在每个数组元素上再次调用jq,只需使用提供循环的第一个调用获取名称即可.

Instead of calling jq again on each array element, just fetch the name with the first call that feeds the loop.

 while read -r job; do
     echo "$job"
 done < <(jq -c '.[].name' < jobs)

(并按照Etan的建议使用read -r).

(and use read -r as suggested by Etan).

如果您需要多个变量,请尝试(例如)

If you need multiple variables, try (for example)

while read -r id
      read -r job; do
    echo "$id: $job"
done < <(jq -c '.[]|.id,.name' < jobs)

这篇关于使用jq和带引号的值处理json数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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