acadavid acadavid - 1 year ago 89
Bash Question

Pass code file as part of object JSON using Curl

I'm trying to write a small script to upload snippets of code to a service provider we use that requires you to pass that code inside a JSON object.

curl -X POST -H "Content-Type: application/json"
-d '{"name":$file_name","script":"$file_content"}'

Where file_content is the javascript code inside my_file. The problem is that printed just like that, the payload is invalid. I'm trying to find a way to read that file in a way that it's valid json. I know it's rather specific but wondering if such command exists.

EDIT: Another option would be to just place the entire JSON object in a file, but i would like to avoid that if possible.

Answer Source

Except in the very simplest of cases, you can't build JSON like that, i.e. by string interpolation. Putting a file's content into a JSON string is not a simple case.

JSON needs to be built by an actual JSON serializer. Python has such a serializer, it would be easy to let Python do the job.

# from
json_escape () {
    printf '%s' $1 | python -c 'import json,sys; print(json.dumps('

so you can do proper value encoding:

json_file_name=$(json_escape "fancy filename")
json_file_content=$(json_escape "$file_content")

curl -X POST -H "Content-Type: application/json" -d "$json"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download