I want to use curl to PUT data. This works:
curl -X PUT --data '{ "xy": [0.6476, 0.2727] }' "http://"
I have a couple of bash variables that I'd like to use in place of the literals:
$key="xy"
$value="[0.6476, 0.2727]"
I've tried replacing the literals with quoted vars, but I get an error 'parameter not available'. I've tried combinations of nested and escaped quotes, but I am not getting anywhere.
This works for me with Node
:
key="xy"
value="[0.6476, 0.2727]"
jsonData=$(node -e "console.log(JSON.stringify({$key: $value}))")
#jsonData output is: {"xy":[0.6476,0.2727]}
curl -X PUT --data $jsonData "http://"
But this only works for Node.js
Developer or you have Node
environment installed.
Well this works for me :
$ key='foo'
$ value='[ bar, bar ]'
$ echo "{ \"$key\": $value }"
{ "foo": [ bar, bar ] }
So this should work for you as well :
curl -X PUT --data "{ \"$key\": $value }" "http://google.com.uy"
Let me know if it helps!
Using jq
(1.6 or later), use the --jsonargs
option to take multiple JSON-encoded values as a JSON array accessible via $ARGS.positional
:
$ key=xy
$ value=(0.6476 0.2727)
$ jq -n '{($k): $ARGS.positional}' --arg k "$key" --jsonargs "${value[@]}"
{
"xy": [
0.6476,
0.2727
]
}
--jsonargs
must come last, so that all remaining arguments are treated as values in the desired array. We use --jsonargs
rather than --args
so that you get an array of floating-point values, rather than an array of strings.
Once you have jq
working, you pipe its output to curl
, which uses -
as the argument to --data
to read the data from the pipe.
jq -n '{($k): $ARGS.positional}' --arg k "$key" --jsonargs "${value[@]}" |
curl -X PUT --data - "http://"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.