使用 Bash 变量构建 JSON 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48470049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 19:05:29  来源:igfitidea点击:

Build a JSON string with Bash variables

jsonbashquoting

提问by nadish

I need to read these bash variables into my JSON string and I am not familiar with bash. any help is appreciated.

我需要将这些 bash 变量读入我的 JSON 字符串中,但我对 bash 并不熟悉。任何帮助表示赞赏。

#!/bin/sh

BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar

JSON_STRING='{"bucketname":"$BUCKET_NAME"","objectname":"$OBJECT_NAME","targetlocation":"$TARGET_LOCATION"}'


echo $JSON_STRING 

回答by chepner

You are better off using a program like jqto generate the JSON, if you don't know ahead of time if the contents of the variables are properly escaped for inclusion in JSON. Otherwise, you will just end up with invalid JSON for your trouble.

jq如果您不提前知道变量的内容是否已正确转义以包含在 JSON 中,则最好使用类似生成 JSON的程序。否则,您最终会遇到无效的 JSON。

BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar

JSON_STRING=$( jq -n \
                  --arg bn "$BUCKET_NAME" \
                  --arg on "$OBJECT_NAME" \
                  --arg tl "$TARGET_LOCATION" \
                  '{bucketname: $bn, objectname: $on, targetlocation: $tl}' )

回答by Diego Torres Milano

You can use printf:

您可以使用printf

JSON_FMT='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}\n'
printf "$JSON_FMT" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION"

much clear and simpler

更加清晰和简单

回答by Cyrus

A possibility:

一个潜在可能:

JSON_STRING='{"bucketname":"'"$BUCKET_NAME"'","objectname":"'"$OBJECT_NAME"'","targetlocation":"'"$TARGET_LOCATION"'"}'

回答by glenn Hymanman

First, don't use ALL_CAPS_VARNAMES: it's too easy to accidentally overwrite a crucial shell variable (like PATH)

首先,不要使用 ALL_CAPS_VARNAMES:很容易意外覆盖关键的 shell 变量(如 PATH)

Mixing single and double quotes in shell strings can be a hassle. In this case, I'd use printf:

在 shell 字符串中混合单引号和双引号可能会很麻烦。在这种情况下,我会使用printf

bucket_name=testbucket
object_name=testworkflow-2.0.1.jar
target_location=/opt/test/testworkflow-2.0.1.jar
template='{"bucketname":"%s","objectname":"%s","targetlocation":"%s"}'

json_string=$(printf "$template" "$BUCKET_NAME" "$OBJECT_NAME" "$TARGET_LOCATION")

echo "$json_string"

For homework, read this page carefully: Security implications of forgetting to quote a variable in bash/POSIX shells

对于家庭作业,请仔细阅读此页面:忘记在 bash/POSIX shell 中引用变量的安全隐患



A note on creating JSON with string concatenation: there are edge cases. For example, if any of your strings contain double quotes, you can broken JSON:

关于使用字符串连接创建 JSON 的注意事项:存在边缘情况。例如,如果您的任何字符串包含双引号,您就可以破坏 JSON:

$ bucket_name='a "string with quotes"'
$ printf '{"bucket":"%s"}\n' "$bucket_name"
{"bucket":"a "string with quotes""}

Do do this more safely with bash, we need to escape that string's double quotes:

使用 bash 更安全地执行此操作,我们需要转义该字符串的双引号:

$ printf '{"bucket":"%s"}\n' "${bucket_name//\"/\\"}"
{"bucket":"a \"string with quotes\""}

回答by Guillermo López Alejos

If you need to build a JSON representation where members mapped to undefined or empty variables should be ommited, then jocan help.

如果您需要构建一个 JSON 表示,其中应该省略映射到未定义或空变量的成员,那么jo可以提供帮助。

#!/bin/bash

BUCKET_NAME=testbucket
OBJECT_NAME=""

JO_OPTS=()

if [[ ! "${BUCKET_NAME}x" = "x" ]] ; then
        JO_OPTS+=("bucketname=${BUCKET_NAME}")
fi

if [[ ! "${OBJECT_NAME}x" = "x" ]] ; then
        JO_OPTS+=("objectname=${OBJECT_NAME}")
fi

if [[ ! "${TARGET_LOCATION}x" = "x" ]] ; then
        JO_OPTS+=("targetlocation=${TARGET_LOCATION}")
fi

jo "${JO_OPTS[@]}"

回答by Prasad Wargad

can be done following way:

可以通过以下方式完成:

JSON_STRING='{"bucketname":"'$BUCKET_NAME'","objectname":"'$OBJECT_NAME'","targetlocation":"'$TARGET_LOCATION'"}'

回答by Hao

For Node.jsDeveloper, or if you have node environment installed, you can try this:

对于Node.jsDeveloper,或者如果你安装了node环境,你可以试试这个:

JSON_STRING=$(node -e "console.log(JSON.stringify({bucketname: $BUCKET_NAME, objectname: $OBJECT_NAME, targetlocation: $TARGET_LOCATION}))")

Advantage of this method is you can easily convert very complicated JSON Object (like object contains array, or if you need int value instead of string) to JSON String without worrying about invalid json error.

这种方法的优点是您可以轻松地将非常复杂的 JSON 对象(如对象包含数组,或者如果您需要 int 值而不是字符串)转换为 JSON 字符串,而无需担心无效的 json 错误。

Disadvantage is it's relying on Node.jsenvironment.

缺点是依赖Node.js环境。