2

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.

2 Answers 2

3

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"
Sign up to request clarification or add additional context in comments.

5 Comments

I think you can probably use single quotes around the JSON string, and then you won't have to escape the double quotes; have not confirmed that though.
@AlexanderMills JSON strings are delimited by double quotes.
Yeah, I tried the single quote thing and it didn't work, so now we know :)
I am going to try this though '"{"foo":"bar"}"' (single quotes around double quotes)
doesn't automaticly escape special characters JSON needs escaped, like \x7F
2

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"

2 Comments

You could also write: ARGS=""; for arg; do printf -v ARGS '%s,"%s"' "$ARGS", "$arg"; done; ARGS=${ARGS#,}
how does this work? I want to put all the arguments to the script $1, $2, $3, etc, into a JSON array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.