Reputation: 4319
I want to send a json-array with POST to a webserver. Everything works fine, except of the wrong contentType of my object.
A "each" loops through my form and adds a pair of values to to two items. Then it adds the two items to an array and gets the next pair:
var jsonArray = []
$(form).each(function() {
.....
item = {};
item["name1"] = value1;
item["name2"] = value2;
jsonString = JSON.stringify(item);
jsonarray.push(jsonString);
...
When i log the result to the console, everything looks great. The POST-method looks like this:
$.ajax ({
type:"POST",
contentType: 'application/json',
url: siteRoot + "/" + ID + "/path",
data: jsonarray,
...
But i am getting an error message from the server which is saying:
Content-type header is "application/json" but body is not a parseble JSON.
Which contentType should i use? If i look through the log file, i am getting output like this:
{"name1":"value1", "name2":"value2"}, {"name1":"value1", "name2":"value2"},...
Do i have to create a special JSON-Object?
Upvotes: 0
Views: 686
Reputation: 2684
The problem is with converting item to JSON and adding to array. This causes quotes around {}. like:
["{"name1":"value1","name2":"value2"}"] // Not Valid
You should add item to array and then convert it
[{"name1":"value1","name2":"value2"}] //valid
Upvotes: 1
Reputation: 24125
The error message is correct because your output isn't a valid JSON string but a string containing JSON strings separated by semicolon. I suggest you serialize the entire array instead of single items. First build your array like this:
var itemsArray = []
$(form).each(function() {
...
item = {};
item["name1"] = value1;
item["name2"] = value2;
itemsArray.push(item);
...
Then POST it like this:
$.ajax ({
type:"POST",
contentType: 'application/json',
url: siteRoot + "/" + ID + "/path",
data: JSON.stringify(itemsArray),
...
If you look at your content it should look like this:
[ {"name1":"value1", "name2":"value2"}, {"name1":"value1", "name2":"value2"}, ... ]
Which is valid JSON and should deserialize into an array of objects.
Upvotes: 2