jq &bash:从变量制作 JSON 数组 [英] jq & bash: make JSON array from variable

查看:27
本文介绍了jq &bash:从变量制作 JSON 数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 jq 从变量值在 bash 中形成一个 JSON.

I'm using jq to form a JSON in bash from variable values.

了解如何制作普通变量

$ VAR="one two three"
$ jq -n "{var:\"$VAR\"}"
{
  "var": "one two three"
}

但是还不能创建数组.我有

But can't make arrays yet. I have

$ echo $ARR
one
two
three

想要得到类似的东西

{
  "arr": ["one", "two", "three"]
}

我只能得到像

$ jq -n "{arr: [\"$ARR\"]}"
{
  "arr": [
    "one\ntwo\nthree"
  ]
}

如何以正确的方式形成JSON数组?jq 能做到吗?

How to form JSON array in a correct way? Can jq ever do that?

EDIT:只有 jq 1.3 时才提出问题.现在,在 jq 1.4 中,可以直接按照我的要求做,就像 @JeffMercado 和 @peak 建议的那样,为他们点赞.不过不会撤销对@jbr 回答的接受.

EDIT: Question was asked when there was only jq 1.3. Now, in jq 1.4, it is possible to do straightly what I asked for, like @JeffMercado and @peak suggested, upvote for them. Won't undo acceptance of @jbr 's answer though.

推荐答案

jq 完全按照你的要求去做.jq 不是生成 JSON 的程序,而是查询它的工具.你用 -n 开关所做的只是将它用作一个漂亮的打印机. 所以如果你想让它打印一个包含一"、二"的数组的对象,三"那么你必须生成它.

jq is doing exactly what you tell it to do. jq is not a program for generating JSON, but a tool for querying it. What you are doing with the -n switch is just using it as a pretty printer. So if you want it to print an object with an array containing "one", "two", "three" then you have to generate it.

VAR="one two three"
VAR=$(echo $VAR | sed -e 's/\(\w*\)/,"\1"/g' | cut -d , -f 2-)
echo "{var: [$VAR]}"

更新

正如 Bryan 和其他人在下面提到的,确实可以使用 jq 生成 JSON,从 1.4 版开始,甚至可以直接执行 OP 要求的操作,例如参见 Jeff 的回答.

As Bryan and others mention below it is indeed possible to generate JSON with jq, and from version 1.4, it's even possible to do what the OP ask directly, see for example Jeff's answer.

这篇关于jq &bash:从变量制作 JSON 数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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