JQ&安培;庆典:让从变量JSON数组 [英] jq & bash: make JSON array from variable

查看:127
本文介绍了JQ&安培;庆典:让从变量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?

修改:有人问的时候,只有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 开关做的只是将它作为pretty打印机。所以,如果你想它来打印一个对象的数组包含一,二,三化,那么你必须生成它。

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

更新

正如布莱恩并更为提下,确实有可能与JQ生成JSON和从版本1.4,它做的甚至有可能是什么OP直接询问的,例如参见杰夫的回答

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&安培;庆典:让从变量JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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