使用curl时遇到问题,从bash中的一个变量发布json对象



所以我正在编写一个脚本,需要创建一个json对象,并用curl发布它。

这是有效的:

curl-头";内容类型:application/json&quot--请求POST——数据"{"_type":"_test","_device":"123.123.123.123","_system":"web services","result":"success","_time":"123","error":"}$data_pipeline

$data_pipeline包含发布请求的URL

如果$json_string包含包含单引号的字符串:

这应该有效,但没有:

curl-头";内容类型:application/json&quot--请求POST--数据$json_string$data_pipeline

首先,我创建了没有单引号的$json_object,并尝试在CURL的命令行中添加它们。如果我不转义单引号,$json_string将作为文本发送,而不是扩展变量。我避开了单引号,但没有帮助,我甚至尝试了双引号,以防需要,但仍然不起作用。只有当我手动放入整个json字符串时,它才有效,但如果我将其放入变量中,它就无效。我该怎么解决这个问题?json是由脚本使用jq动态创建的,json是有效的,因为我可以手动成功运行post,我只需要它来处理一个变量。没有单引号就无法工作,但当我使用变量来保存json时,单引号就不起作用,无论我是将单引号放在变量中,还是尝试在变量之外进行。。。我该如何解决这个问题?

json对象是用以下代码构建的:

json_string='$( jq -n 
--arg _type "$_type" 
--arg _device "$_device" 
--arg _system "$_system" 
--arg result "$result" 
--arg _time "$_time" 
--arg error "$error" 
'{_type: $_type, _device: $_device, _system: $_system, result: $result, _time: $_time, error: $error}' )'

最初我创建的json_string没有',但我添加了它,试图将单引号包裹在json周围。

谢谢!

#!/bin/bash
_type="hello"
# let's have some fun
_device="single'quote"
_system='double"quote'
error='multi
line'
encode()
{
printf "%s" "$1" | sed 's/"/%22/' | tr 'n' ' '
}
# you don't need encode() if your strings are not json-offensive
json_string="{
_type: "$_type"
_device: "$_device"
_system: "$(encode "$_system")"
error: "$(encode "$error")"
}"
set -x
curl 
-X POST 
-d "$json_string" 
-H 'content-type: application/json' 
http://httpbin.org/anything

输出:

+ curl -X POST -d '{
_type: "hello"
_device: "single'''quote"
_system: "double%22quote"
error: "multi line"
}' -H 'content-type: application/json' http://httpbin.org/anything
{
"args": {}, 
"data": "{nt_type: "hello"nt_device: "single'quote"nt_system: "double%22quote"nterror: "multi line"n}", 
"files": {}, 
"form": {}, 
"headers": {
"Accept": "*/*", 
"Content-Length": "92", 
"Content-Type": "application/json", 
"Host": "httpbin.org", 
"User-Agent": "curl/7.58.0", 
}, 
"json": null, 
"method": "POST", 
"url": "http://httpbin.org/anything"
}

最新更新