acrazing
acrazing

Reputation: 2284

How to write oneline string in multipe lines?

I want to send a big json with long string field by curl, how should I crop it to multiple lines? For example:

curl -X POST 'localhost:3000/upload' \
  -H 'Content-Type: application/json'
  -d "{
    \"markdown\": \"# $TITLE\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\nsome content with multiple lines....\\n\\n\"
  }"

Upvotes: 1

Views: 522

Answers (3)

janos
janos

Reputation: 124646

You can split anything to multiple lines using the technique already in your post, by terminating lines with \. If you need to split in the middle of a quoted string, terminate the quote and start a new one. For example these are equivalent:

echo "foobar"
echo "foo""bar"
echo "foo"\
     "bar"

But for your specific example I recommend a much better way. Creating the JSON in a double-quoted string is highly error prone, because of having to escape all the internal double-quotes, which becomes hard to read and maintain as well. A better alternative is to use a here-document, pipe it to curl, and use -d@- to make it read the JSON from stdin. Like this:

formatJson() {
    cat << EOF
{
  "markdown": "some content with $variable in it"
}
EOF
}

formatJson | curl -X POST 'localhost:3000/upload' \
  -H 'Content-Type: application/json'
  -d@-

Upvotes: 2

chepner
chepner

Reputation: 531165

Use a tool like jq to generate your JSON, rather than trying to manually construct it. Build the multiline string in the shell, and let jq encode it. Most importantly, this avoids any potential errors that could arise from TITLE containing characters that would need to be correctly escaped when forming your JSON value.

my_str="# $TITLE
some content with multiple lines...
some content with multiple lines...
some content with multiple lines..."

my_json=$(jq --argjson v "$my_str" '{markdown: $v}')

curl -X POST 'localhost:3000/upload' \
  -H 'Content-Type: application/json' \
  -d "$my_json"

curl has the ability to read the data for -d from standard input, which means you can pipe the output of jq directly to curl:

jq --argjson v "$my_str" '{markdown: $v}' | curl ... -d@-

Upvotes: 2

Rafael
Rafael

Reputation: 7746

If I were you, I'd save the JSON to a file:

curl -X POST 'localhost:3000/upload' \
    -H 'Content-Type: application/json' \
    -d "$(cat my_json.json)"

Upvotes: 1

Related Questions