如何将bash数组格式化为JSON数组 [英] How to format a bash array as a JSON array

查看:188
本文介绍了如何将bash数组格式化为JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个bash数组

X=("hello world" "goodnight moon")

我想变成一个json数组

That I want to turn into a json array

["hello world", "goodnight moon"]

是否有一种好方法可以将其转换为json字符串数组,而无需遍历子shell中的键?

Is there a good way for me to turn this into a json array of strings without looping over the keys in a subshell?

(for x in "${X[@]}"; do; echo $x | sed 's|.*|"&"|'; done) | jq -s '.'

这显然行不通

echo "${X[@]}" | jq -s -R '.'

推荐答案

您可以执行以下操作:

X=("hello world" "goodnight moon")
printf '%s\n' "${X[@]}" | jq -R . | jq -s .

输出

[
  "hello world",
  "goodnight moon"
]

这篇关于如何将bash数组格式化为JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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