使用Curl将代码文件作为对象JSON的一部分传递

时间:2016-11-17 14:59:50

标签: json bash shell curl

我试图编写一个小脚本来将代码片段上传到我们使用的服务提供程序,这需要您将代码传递到JSON对象中。

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

其中file_content是my_file中的javascript代码。问题是打印就像这样,有效载荷无效。我试图找到一种以有效json方式读取该文件的方法。我知道这是相当具体的,但想知道这样的命令是否存在。

编辑:另一种选择是将整个JSON对象放在一个文件中,但如果可能的话我想避免这种情况。

2 个答案:

答案 0 :(得分:1)

除非在最简单的情况下,你不能像那样构建JSON,即通过字符串插值。将文件的内容放入JSON字符串并不是一个简单的例子。

JSON需要由实际的JSON序列化程序构建。 Python有这样的序列化程序,让Python完成这项任务很容易。

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

所以你可以进行正确的值编码:

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

答案 1 :(得分:0)

使用php5的JSON序列化功能:

jq