Reputation: 4265
I am trying to submit some JSON to my web app and I want the JSON to be like this:
{
"thing1" :
{
"something" : "hello"
},
"list_of_things" :
[
{
"item1" : "hello"
},
{
"item2" : "hello"
}
]
}
Here I have one JSON object and a JSON array that holds JSON objects. When I create the data to submit in Javascript I do:
form = {
"thing1" : {
"something" : somethingVariable
},
"list_of_things" : listArray
}
Here 'listArray' is a Javascript Array object of Javascript hash objects. I submit this using jQuery's ajax method but instead of javascript array displaying as the JSON array desired it converts it to a series of JSON objects like this:
{ "1" : { "thing1" : "something" }, "2" : { "thing2" : "something" }...
How can I get the array to be submitted as an array rather than be converted into a series of JSON objects with the array indexes as keys?
EDIT#1: 'listArray' is a simple Javascript array that is defined like so:
var listArray = new Array();
listArray.push({ "thing1" : "something" });
listArray.push({ "thing2" : "something" });
EDIT#2: 'form' is sent to the server with the following call:
$.ajax({
type: 'POST',
url: '/url',
dataType: "json",
data: form,
success: function(data) {
/* success code here */
}
});
Upvotes: 3
Views: 5052
Reputation: 29841
Have a look here. If you are truly trying to post JSON you will need to send the string, not an object literal. You could use JSON.stringify
(or a more supported JSON solution) on form
.
$.ajax({
url: "/url",,
dataType: "json",
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify(form)
});
Upvotes: 3