Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

Convert arguments of a bash script to a JSON array for a web service

I have a web service that requires a list of arguments in a JSON format. For instance, the JSON it could handle is like this:

{
  "args": ["basharg1", "bash arg 2 with spaces", "lastargs"]
}

How can I easily transform the arguments to a bash script to build a string that holds this kind of JSON? That string would then be used by curl to pas it to the web service.

Upvotes: 2

Views: 2468

Answers (2)

Greg Edwards
Greg Edwards

Reputation: 658

On a Mac, a shorter version that uses glenn_jackman's approach is:

ARGS=""; for arg; do ARGS=$(printf '%s"%s"' "$ARGS", "$arg"); done;
ARGS=${ARGS#,}
JSON="{ \"args\": [$ARGS] }"
echo "$JSON"

Upvotes: 3

Jean-Philippe Pellet
Jean-Philippe Pellet

Reputation: 60006

Here's how I ended up doing it. Feel free to suggest improvements.

#!/bin/bash

ARGS="\"$1\""
shift

while (( "$#" )); do
    ARGS="$ARGS, \"$1\""
    shift
done

ARGUMENTS_JSON="{ \"args\": [$ARGS] }"

echo "$ARGUMENTS_JSON"

Upvotes: 2

Related Questions