Reputation: 11100
I have an object like this:
{
"someList": [
{
"accountNumber": 123456,
"balance": 3.14
},
{
"accountNumber": 7890,
"balance": 2.72
}
],
"numErrors": 0,
"duration": 12345
}
How do I convert it to x-www-form-urlencoded in order to send it in a POST request using e.g. the curl command line? I know about "key1=value1&key2=value2"
but I'm particularly buffled about how to send whole lists containing structures.
Upvotes: 0
Views: 1016
Reputation: 3423
I guess it all depends on the server you're POSTing to.
If it accepts your prettified JSON in urlencoded form, then --data-urlencode @input.json
would suffice for curl
. If it doesn't and you have to minify / serialize it first, then a JSON-parser like xidel can help:
$ xidel -s input.json -e 'serialize($json,{"method":"json"})'
{"someList":[{"accountNumber":123456,"balance":3.14},{"accountNumber":7890,"balance":2.72}],"numErrors":0,"duration":12345}
$ xidel -s input.json -e 'serialize($json,{"method":"json"})' | \
curl -s --data-urlencode @- "<url>"
$ xidel -s input.json -e 'uri-encode(serialize($json,{"method":"json"}))'
%7B%22someList%22%3A%5B%7B%22accountNumber%22%3A123456%2C%22balance%22%3A3.14%7D%2C%7B%22accountNumber%22%3A7890%2C%22balance%22%3A2.72%7D%5D%2C%22numErrors%22%3A0%2C%22duration%22%3A12345%7D
$ xidel -s input.json -e 'uri-encode(serialize($json,{"method":"json"}))' | \
curl -s -d @- "<url>"
xidel
can also do POST requests:
$ xidel -s \
-d '{uri-encode(serialize(json-doc("input.json"),{"method":"json"}))}' \
"<url>" \
-e '$raw'
$ xidel -s input.json -e '
x:request({
"post":uri-encode(serialize($json,{"method":"json"})),
"url":"<url>"
})/raw
'
-e '$raw'
shows the raw output, similar to curl
.xidel -s input.json -d '...$json...'
doesn't work, because -d
is evaluated before the input is read, hence json-doc()
to open files/urls in-query.Upvotes: 1