bash - Pass code file as part of object JSON using Curl -


i'm trying write small script upload snippets of code service provider use requires pass code inside 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 javascript code inside my_file. problem printed that, payload invalid. i'm trying find way read file in way it's valid json. know it's rather specific wondering if such command exists.

edit: option place entire json object in file, avoid if possible.

except in simplest of cases, can't build json that, i.e. string interpolation. putting file's content json string not simple case.

json needs built actual json serializer. python has such serializer, easy let python job.

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

so can 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

Popular posts from this blog

account - Script error login visual studio DefaultLogin_PCore.js -

xcode - CocoaPod Storyboard error: -