acadavid acadavid - 15 days ago 5
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.

file_content=$(<my_file.js)
curl -X POST -H "Content-Type: application/json"
-d '{"name":$file_name","script":"$file_content"}' https://someservice.com/api/endpoint


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

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 http://stackoverflow.com/a/13466143
json_escape () {
    printf '%s' $1 | python -c 'import json,sys; print(json.dumps(sys.stdin.read()))'
}

so you can do proper value encoding:

file_content=$(<my_file.js)
json_file_name=$(json_escape "fancy filename")
json_file_content=$(json_escape "$file_content")
json='{"name":'$json_file_name',"script":'$json_file_content'}'

curl -X POST -H "Content-Type: application/json" -d "$json" https://someservice.com/api/endpoint
Comments