web-dev-qa-db-fra.com

Construire une chaîne JSON avec des variables Bash

J'ai besoin de lire ces variables bash dans ma chaîne JSON et je ne suis pas familier avec bash. toute aide est appréciée.

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

Vous feriez mieux d’utiliser un programme tel que jq pour générer le JSON, si vous ne savez pas à l’avance si le contenu des variables est correctement échappé pour l’inclusion dans JSON. Sinon, vous ne vous retrouverez qu'avec un code JSON non valide.

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}' )
51
chepner

Vous pouvez utiliser printf:

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

beaucoup plus clair et simple

15
Diego Torres Milano

Une possibilité:

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

Tout d'abord, n'utilisez pas ALL_CAPS_VARNAMES: il est trop facile d'écraser accidentellement une variable Shell cruciale (comme PATH).

Mélanger des guillemets simples et doubles dans les chaînes du shell peut être un problème. Dans ce cas, j'utiliserais 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"

Pour les devoirs, lisez attentivement cette page: Conséquences pour la sécurité d’oublier de citer une variable dans les shells POSH/bash


Une note sur la création de JSON avec concaténation de chaînes: il existe des cas Edge. Par exemple, si l'une de vos chaînes contient des guillemets doubles, vous pouvez rompre le code JSON:

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

Faites ceci avec plus de sécurité avec bash, nous devons échapper aux guillemets de cette chaîne:

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