【问题标题】:Parsing json using jq depending upon the type根据类型使用 jq 解析 json
【发布时间】:2017-07-03 01:03:11
【问题描述】:

我想根据它的类型解析一个 json,因为它有时会发生变化。如果 json 是一个数组,我需要获取第一个元素,或者如果不是,我只需要那个元素!下面是我尝试过的一个更简单的版本。

#!/bin/bash

word='[0,1]'
word=$(echo $word | jq 'if type=="array" then "'$word[0]'" else "'$word'" end')
echo $word

它输出"[0,1][0]",正如我预期的那样,将传递条件分配给变量,它只是0。因为在下面的情况下它只是打印“是”。

#!/bin/bash

word='[0,1]'
word=$(echo $word | jq 'if type=="array" then "yes" else "no" end')
echo $word

为什么会有区别以及如何实现前者?

【问题讨论】:

  • 你用文字双引号明确地包围你的价值。这意味着您要求将其视为字符串,而不是提取列表第一个元素的表达式。
  • 如果数组为空怎么办?
  • 我在主代码中以不同的方式处理了这一点

标签: arrays json bash parsing jq


【解决方案1】:

您可以使用.[0] 返回第一个数组项:

echo "$word" | jq 'if type=="array" then .[0] else . end'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 1970-01-01
    • 2018-09-01
    • 2018-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多