Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to PUT a json object with an array using curl

Tags:

json

curl

I have a series of data to enter into database. The user interface to enter the data isn't good for bulk entry, so I'm trying to formulate a command line equivalent. When I examine the network request of the UI in chrome, I see a PUT request of a json object. When I try to replicate the request

curl -H 'Accept: application/json' -X PUT '{"tags":["tag1","tag2"],"question":"Which band?","answers":[{"id":"a0","answer":"Answer1"},{"id":"a1","answer":"answer2"}]}' http://example.com/service` 

I get a error

curl: (3) [globbing] nested braces not supported at pos X

Where X is the character position of first "[".

How can I PUT a json object that includes an array?

like image 229
Miles Libbey Avatar asked Mar 15 '13 05:03

Miles Libbey


People also ask

Can a JSON object contain an array?

Arrays in JSON are almost the same as arrays in JavaScript. In JSON, array values must be of type string, number, object, array, boolean or null. In JavaScript, array values can be all of the above, plus any other valid JavaScript expression, including functions, dates, and undefined.

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.

How do I write an array to a JSON file?

You convert the whole array to JSON as one object by calling JSON. stringify() on the array, which results in a single JSON string. To convert back to an array from JSON, you'd call JSON. parse() on the string, leaving you with the original array.


2 Answers

Your command line should have a -d/--data inserted before the string you want to send in the PUT, and you want to set the Content-Type and not Accept.

curl -H 'Content-Type: application/json' -X PUT -d '[JSON]' \      http://example.com/service 

Using the exact JSON data from the question, the full command line would become:

curl -H 'Content-Type: application/json' -X PUT \     -d '{"tags":["tag1","tag2"],          "question":"Which band?",          "answers":[{"id":"a0","answer":"Answer1"},                     {"id":"a1","answer":"answer2"}]}' \     http://example.com/service 

Note: JSON data wrapped only for readability, not valid for curl request.

like image 139
Daniel Stenberg Avatar answered Oct 04 '22 12:10

Daniel Stenberg


Although the original post had other issues (i.e. the missing "-d"), the error message is more generic.

curl: (3) [globbing] nested braces not supported at pos X

This is because curly braces {} and square brackets [] are special globbing characters in curl. To turn this globbing off, use the "-g" option.

As an example, the following Solr facet query will fail without the "-g" to turn off curl globbing: curl -g 'http://localhost:8983/solr/query?json.facet={x:{terms:"myfield"}}'

like image 45
Yonik Avatar answered Oct 04 '22 11:10

Yonik