English 中文(简体)
1. 建立具有巴什变量的JSON
原标题:Build a JSON string with Bash variables

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

#!/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 
最佳回答

如果你不事先知道这些变量的内容被适当抹去列入初等人物的话,那么你就更不用使用jq之类的方案来生成初等人物。 否则,你会因为你的麻烦而以残疾的智者告终。

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}  )
问题回答

您可使用<条码>。

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

非常明确和简单

A possibility:

#!/bin/bash 

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

# one line
JSON_STRING= {"bucketname":" "$BUCKET_NAME" ","objectname":" "$OBJECT_NAME" ","targetlocation":" "$TARGET_LOCATION" "} 

# multi-line
JSON_STRING="{
"bucketname":"${BUCKET_NAME}",
"objectname":"${OBJECT_NAME}",
"targetlocation":"${TARGET_LOCATION}"
}"

# [optional] validate the string is valid json
echo "${JSON_STRING}" | jq

我必须努力寻找一切可能的办法,在指挥要求中处理枪匹马, 请看以下法典,看一看如果使用不当,为什么使用单一报价会失败。

# Create Release and Tag commit in Github repository

# returns string with in-place substituted variables 

json=$(cat <<-END
    {
        "tag_name": "${version}", 
        "target_commitish": "${branch}", 
        "name": "${title}", 
        "body": "${notes}", 
        "draft": ${is_draft}, 
        "prerelease": ${is_prerelease} 
    }
END
)

# returns raw string without any substitutions
# single or double quoted delimiter - check HEREDOC specs

json=$(cat <<-!"END"   # or  END  
    {
        "tag_name": "${version}", 
        "target_commitish": "${branch}", 
        "name": "${title}", 
        "body": "${notes}", 
        "draft": ${is_draft}, 
        "prerelease": ${is_prerelease} 
    }
END
)
# prints fully formatted string with substituted variables as follows:

echo "${json}"  
{ 
    "tag_name" : "My_tag", 
    "target_commitish":"My_branch"
    ....
}

http://www.un.org/Depts/DGACM/index_french.htm

# enclosing in single quotes means no variable substitution 
# (treats everything as raw char literals)

echo  ${json}    
${json} 

echo  "${json}"    
"${json}" 
# enclosing in single quotes and outer double quotes causes
# variable expansion surrounded by single quotes(treated as raw char literals).

echo " ${json} " 
 { 
    "tag_name" : "My_tag", 
    "target_commitish":"My_branch"
    ....
} 

www.un.org/Depts/DGACM/index_spanish.htm 说明2:与线路终点站保持距离

  • Note the json string is formatted with line terminators such as LF
  • or carriage return (if its encoded on windows it contains CRLF )
  • using (translate) tr utility from shell we can remove the line terminators if any

# following code serializes json and removes any line terminators 
# in substituted value/object variables too

json=$(echo "$json" | tr -d  
  | tr -d  
  )
# string enclosed in single quotes are still raw literals

echo  ${json}    
${json} 

echo  "${json}"    
"${json}" 
# After CRLF/LF are removed

echo " ${json} " 
 { "tag_name" : "My_tag", "target_commitish":"My_branch" .... } 

说明3:格式

  • while manipulating json string with variables, we can use combination of and " such as following, if we want to protect some raw literals using outer double quotes to have in place substirution/string interpolation:
# mixing   and " 

username=admin
password=pass

echo "$username:$password"
admin:pass

echo "$username" : "$password"
admin:pass

echo "$username" [${delimiter}] "$password"
admin[${delimiter}]pass

www.un.org/Depts/DGACM/index_chinese.htm

  • Following curl request already removes existing (ie serializes json)
response=$(curl -i 
            --user ${username}:${api_token} 
            -X POST 
            -H  Accept: application/vnd.github.v3+json  
            -d "$json" 
            "https://api.github.com/repos/${username}/${repository}/releases" 
            --output /dev/null 
            --write-out "%{http_code}" 
            --silent
          )

So when using it for command variables, validate if it is properly formatted before using it :)

第一,不使用任何电离层电离层电离层电离层:它很容易意外地超出临界壳变量(如PATH)。

在壳体中混合单体和双面字可以是一片。 在此情况下,我使用<编码>印有<>。

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"

“家庭工作”:,“因在bash/POSIX 壳中引述一个变量的安全影响”


一份关于建立有色人种的JSON的说明:有edge。 例如,如果你的任何扼杀都含有双重引言,你可以破除:

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

要想以比什安全的方式做到这一点,我们需要避免这种扼杀双面的quot:

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

如果你需要建立一位由成员规划为未界定或空洞变数的名人代表,则可以帮助:https://github.com/jpmens/jo”rel=“noestlow noreferer”>。

#!/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[@]}"

以上指挥的产出只是(表示没有<编码>目标名称<>/代码>和<代码> 目标<>/代码>成员):

{"bucketname":"testbucket"}

can be done following way:

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

www.un.org/Depts/DGACM/index_french.htm 培养者,或者如果你安装了天线,你可以尝试:

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.

Disadvantage is it s relying on Node.js environment.

For a general case of building JSON from bash with arbitrary inputs, many of the previous responses (even the high voted ones with jq) omit cases when the variables contain " double quote, or newline escape string, and you need complex string concatenation of the inputs.

When using jq you need to printf %b the input first to get the converted to real newlines, so that once you pass through jq you get back and not \n.

I found this with version with nodejs to be quite easy to reason about if you know javascript/nodejs well:

TITLE= Title 
AUTHOR= Bob 
JSON=$( TITLE="$TITLE" AUTHOR="$AUTHOR" node -p  JSON.stringify( {"message": `Title: ${process.env.TITLE}

Author: ${process.env.AUTHOR}`} )  )

It s a bit verbose due to process.env. but allows to properly pass the variables from shell, and then format things inside (nodejs) backticks in a safe way.

产出:

printf "%s
" "$JSON"
{"message":"Title: Title

Author: Bob"}

(Note: when having a variable with always use printf "%s " "$VAR" and not echo "$VAR", whose output is platform-dependent! See here for details)

Similar thing with jq would be

TITLE= Title 
AUTHOR= Bob  
MESSAGE="Title: ${TITLE}

Author: ${AUTHOR}"
MESSAGE_ESCAPED_FOR_JQ=$(printf %b "${MESSAGE}")
JSON=$( jq  {"message": $jq_msg}  --arg jq_msg "$MESSAGE_ESCAPED_FOR_JQ" --null-input --compact-output --raw-output --monochrome-output )

(最后两段在座标时并不必要,但我刚刚添加,以便在你操作<代码>jq时,产出不变。) 一级指挥。

这些解决办法是很晚才提出的,但我认为,这些解决办法本身比以前的建议(避免援引和教唆的复杂性)更为简单。

    BUCKET_NAME=testbucket
    OBJECT_NAME=testworkflow-2.0.1.jar
    TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar
    
    # Initial unsuccessful solution
    JSON_STRING= {"bucketname":"$BUCKET_NAME","objectname":"$OBJECT_NAME","targetlocation":"$TARGET_LOCATION"} 
    echo $JSON_STRING 
    
    # If your substitution variables have NO whitespace this is sufficient
    JSON_STRING=$(tr -d [:space:] <<JSON
    {"bucketname":"$BUCKET_NAME","objectname":"$OBJECT_NAME","targetlocation":"$TARGET_LOCATION"}
    JSON
    )
    echo $JSON_STRING 
    
    # If your substitution variables are more general and maybe have whitespace this works
    JSON_STRING=$(jq -c . <<JSON
    {"bucketname":"$BUCKET_NAME","objectname":"$OBJECT_NAME","targetlocation":"$TARGET_LOCATION"}
    JSON
    )
    echo $JSON_STRING 
    
    #... A change in layout could also make it more maintainable
    JSON_STRING=$(jq -c . <<JSON
    {
       "bucketname" : "$BUCKET_NAME",
       "objectname" : "$OBJECT_NAME",
       "targetlocation" : "$TARGET_LOCATION"
    }
    JSON
    )
    echo $JSON_STRING

您可使用<代码>envsubst:

  export VAR="some_value_here"
  echo  {"test":"$VAR"}  | envsubst > json.json

也可以是“模板”文件:

//json.template
{"var": "$VALUE", "another_var":"$ANOTHER_VALUE"}

因此,在你能够做到之后:

export VALUE="some_value_here"
export ANOTHER_VALUE="something_else"
cat  json.template | envsubst > misha.json

Bash will not insert variables into a single-quote string. In order to get the variables bash needs a double-quote string. You need to use double-quote string for the JSON and just escape double-quote characters inside JSON string. Example:

#!/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 

如果你有点 no子,并且在全球得到最小安装:

jc() {
    node -p "JSON.stringify(require( minimist )(process.argv), (k,v) => k== _ ?undefined:v)" -- "$@"
}
jc --key1 foo --number 12 --boolean 
    --under_score  abc def  -- white space       
# {"key1":"foo","number":12,"boolean":true,"under_score":"abc def","white space":"   "}

您可以 cur笑或说什么:

curl --data "$(jc --type message --value  hello world! )" 
    --header  content-type: application/json  
    http://server.ip/api/endpoint

注意:

jc --m.room.member @gholk:ccns.io
# {"m":{"room":{"member":"@gholk:ccns.io"}}}

供世界妇女论坛宏观组合使用:

JSON_CONFIG=$( jq -n 
   --arg bucket_name "$BUCKET_NAME" 
   --arg kms_key_arn "$KMS_KEY_ARN" 
    {"s3Destination":{"bucketName":$bucket_name,"kmsKeyArn":$kms_key_arn}} 
)

aws macie2 put-classification-export-configuration --configuration "$JSON_CONFIG"

你们只能发出这样的呼吁,以印刷“智者”。

#!/bin/sh
BUCKET_NAME=testbucket

OBJECT_NAME=testw或kflow-2.0.1.jar

TARGET_LOCATION=/opt/test/testw或kflow-2.0.1.jar

echo  { "bucketName": " "$BUCKET_NAME" ", "objectName": " "$OBJECT_NAME" ", "targetLocation": " "$TARGET_LOCATION" " } 

JSON_STRING= { "bucketName": " "$BUCKET_NAME" ", "objectName": " "$OBJECT_NAME" ", "targetLocation": " "$TARGET_LOCATION" " } 
echo $JOSN_STRING

with jq "@sh" we can translate jq string array to bash array:

#!/bin/bash

set -eufo pipefail
#set -x

# $1 should calculate an json array from input
jq_array() {
  jq "$1"
}

# $1 is an array name
# $2 should calculate an json array from input
read_jq_array() {
  eval unset "$1"
  eval "$(jq -r  ([" "$1" =("] + [ "$2"  | @sh ] + [")"]) | join(" ") )"
}

dump_array() {
  printf "[%s]
" "$@"
}

input_string= ["a     b", "2"
new line", "1	2	3"] 

# view the input
jq_array  .  <<< "$input_string"

arr=()

# transform to bash array
read_jq_array arr . <<< "$input_string"

# view the result
dump_array "${arr[@]}"

bash功能read_jq_array par子阵列和val子分配到目标篮子。 所有特殊特性线新行、表格、空间、配额都按预期保持不变。





相关问题
Parse players currently in lobby

I m attempting to write a bash script to parse out the following log file and give me a list of CURRENT players in the room (so ignoring players that left, but including players that may have rejoined)...

encoding of file shell script

How can I check the file encoding in a shell script? I need to know if a file is encoded in utf-8 or iso-8859-1. Thanks

Bash usage of vi or emacs

From a programming standpoint, when you set the bash shell to use vi or emacs via set -o vi or set -o emacs What is actually going on here? I ve been reading a book where it claims the bash shell ...

Dynamically building a command in bash

I am construcing a command in bash dynamically. This works fine: COMMAND="java myclass" ${COMMAND} Now I want to dynamically construct a command that redirectes the output: LOG=">> myfile.log ...

Perform OR on two hash outputs of sha1sum

I want perform sha1sum file1 and sha1sum file2 and perform bitwise OR operation with them using bash. Output should be printable i.e 53a23bc2e24d039 ... (160 bit) How can I do this? I know echo $(( ...

Set screen-title from shellscript

Is it possible to set the Screen Title using a shell script? I thought about something like sending the key commands ctrl+A shift-A Name enter I searched for about an hour on how to emulate ...

热门标签