Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

curl with json array

Tags:

json

bash

curl

The first command works and the second doesn't. What do I need to change to allow the json array to work? Thank you in advance.

command #1:

curl -d '{"uid":"TEST", "object":"TEST"}' \
        -H "Content-Type: application/json" \
        -X POST http://WEBSERVER/api/v1/inventory

command #2

curl -d '{"uid":"TEST","object":["server1", "server2", "server3"]}' \
        -H "Content-Type: application/json" \
        -X POST http://WEBSERVER/api/v1/inventory
like image 837
dev_oper Avatar asked Nov 19 '25 12:11

dev_oper


1 Answers

Your curl syntax is fine, you could test by using httpbin.org, for example:

$ curl -d '{"uid":"TEST","object":["server1", "server2", "server3"]}' \
    -H "Content-Type: application/json" \
    -X POST http://httpbin.org/post

Returns:

{
  "args": {},
  "data": "{\"uid\":\"TEST\",\"object\":[\"server1\", \"server2\", \"server3\"]}",
  "files": {},
  "form": {},
  "headers": {
    "Accept": "*/*",
    "Connection": "close",
    "Content-Length": "57",
    "Content-Type": "application/json",
    "Host": "httpbin.org",
    "User-Agent": "curl/7.54.0"
  },
  "json": {
    "object": [
      "server1",
      "server2",
      "server3"
    ],
    "uid": "TEST"
  },
  "origin": "x.x.x.x",
  "url": "http://httpbin.org/post"
}

You indeed could pipe the result and verify the output with your input:

$ curl -d '{"uid":"TEST","object":["server1", "server2", "server3"]}' \
    -H "Content-Type: application/json" \
    -X POST http://httpbin.org/post -s | jq -r '.data'

It will print:

{"uid":"TEST","object":["server1", "server2", "server3"]}

Probably the server you are using to post data don't accept your request, check the returned status code, could give a clue, maybe is a 400 (bad request) or a 406 (not acceptable) etc, just in case here is a list of possible status codes.

like image 133
nbari Avatar answered Nov 21 '25 07:11

nbari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!