There is no need to wrap the array in another object with a data property. The array by itself is valid JSON:
post_params = JSON.stringify([ { 'name' : 'Alice', 'age' : 15 },
{ 'name' : 'Bob', 'age' : 20 },
...
]);
post(url, post_params);
Just make sure your API expects this array as well.
Answer from Adam Liechty on Stack OverflowThere is no need to wrap the array in another object with a data property. The array by itself is valid JSON:
post_params = JSON.stringify([ { 'name' : 'Alice', 'age' : 15 },
{ 'name' : 'Bob', 'age' : 20 },
...
]);
post(url, post_params);
Just make sure your API expects this array as well.
Basically, the answer I was looking for was:
- There is no need to use
Content-Type: application/x-www-form-urlencodedwhich is standard in web; instead,Content-Type: application/jsonshould be used, The whole HTTP request then looks as follows:
POST /whatever HTTP/1.1 Host: api.example.com Content-Type: application/json [ { 'name': 'Alice', 'age': 15 }, { 'name': 'Bob', 'age': 20 }, ... ]
Passing an array in form-data, JSON Format
POST Request: dynamically send an array (list) in a JSON
Post an array in a HTTP request
What is the "best practice" for sending an array of objects to the server?
In JavaScript / JSON arrays are 0 based indexed data structures. What you are using here is more like a Map:
var jsonArray = [];
jsonArray["company_name"]=company_name ;
In JavaScript you cannot use arrays like this (well you can, but it is probably not what you want). For a data structure like a map that maps strings to objects rather then an index to objects, just use an object.
Or in short: Use var jsonArray = {}; rather than var jsonArray = []; The {} will create an object that you can assign properties to like you did. And JSON.stringify will correctly translate this into a JSON string like this:
{ "property": value, "otherProperty", otherValue }
Do something like this.
$.ajax({
url: url,
type: "POST",
dataType: 'json',
contentType: 'application/json; charset=UTF-8',
data: JSON.parse(JSON.stringify(jsonArray)),
success: function(response) {
//Some Code here
}
});
Short backstory: I learned Angular straight out of uni and thought it might be useful to get some basic knowledge about how the web works on a fundamental level. So I decided to build a small MPA with Go as a backend language.
Now I got to a problem that would be trivial to solve in Angular but I am having trouble solving with server-side rendering:
Imagine a traditional form where I can add and remove items (kind of like a shopping cart) with javascript and once I am done I can click on "Save" and all items are send to the server with a POST request. The special thing is that the items are complex objects with multiple properties, not just strings.
I would prefer to use a form and just submit it, but it feels like this type of complex data does not go well with a form. I know that PHP can handle this kind of structure (https://stackoverflow.com/questions/34313657/html-form-post-an-array-of-objects), but I don't think this is standard, since there doesn't seem to be a way to do this in Go. So is my only choice to send JSON? But how do I transform my input values to JSON?
So the question is this: what is the best practice when I need to send an array of objects to the server and how would a person have solved this 10 or 15 years ago?
You need to suffix your variable name with [] like this:

If that doesn't work, try not putting indexes in brackets:
my_array[] value1
my_array[] value2
Note:
If you are using the postman packaged app, you can send an array by selecting
raw/json(instead ofform-data). Also, make sure to setContent-Typeasapplication/jsoninHeaderstab. Here is example for raw data{"user_ids": ["123" "233"]}, don't forget the quotes!If you are using the postman REST client you have to use the method I described above because passing data as raw (json) won't work. There is a bug in the postman REST client (At least I get the bug when I use
0.8.4.6).
For me did not work with array[0], array1, .. or array[], array[], ... .
It works more simply:

The problem your having is this string is NOT Proper JSON: [500,'hello world']
this would be proper JSON [500,"hello world"]. JSON is very strict on formatting and requires that all string values be wrapped in double quotes and NEVER single quotes.
the proper thing to do to avoid problems, would be to use the php functions json_encode() and json_decode()
for example,
<?php
$myarray[] = 500;
$myarray[] = "hello world";
$myjson = json_encode($myarray);
?>
<form name="input" action="post.php">
<input type="hidden" name="json" value="<?php echo $myjson ?>" />
<input type="submit" value="Submit">
</form>
and in the post.php you would read it like so,
<?php
$posted_data = array();
if (!empty($_POST['json'])) {
$posted_data = json_decode($_POST['json'], true);
}
print_r($posted_data);
?>
the true flag in json_decode() tells the function you want it as an associative array and not a PHP object, which is its default behavior.
the print_r() function will output the php structure of the converted JSON array:
Array(
[0] => 500
[1] => hello world
)
Is the API a 3rd party on or made by you?
If it is yours, consume the data sent by your form should be as simple as this on your API:
<?php
$data = json_decode($_REQUEST['json']);
echo $data[0]; // Should output 500
echo $data[1]; // Should output hello world
If it is a 3rd party, probably they expect you to send the json in post body. To accomplish that, follow this post: How to post JSON to PHP with curl.
-----------------------------------test.Order.java-----------------------------------
package test;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Order {
@SerializedName("product_id")
@Expose
private String productId;
@SerializedName("qty")
@Expose
private String qty;
@SerializedName("price")
@Expose
private String price;
@SerializedName("total")
@Expose
private String total;
@SerializedName("product_name")
@Expose
private String productName;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getQty() {
return qty;
}
public void setQty(String qty) {
this.qty = qty;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getTotal() {
return total;
}
public void setTotal(String total) {
this.total = total;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
}
-----------------------------------test.TestClass.java-----------------------------------
package test;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class TestClass {
@SerializedName("user_id")
@Expose
private String userId;
@SerializedName("username")
@Expose
private String username;
@SerializedName("order")
@Expose
private List<Order> order = null;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public List<Order> getOrder() {
return order;
}
public void setOrder(List<Order> order) {
this.order = order;
}
}
Use this two Class.Load data to this class. And use GSON Library.
Gson gson= new GSON();
String requiredJson= gson.toJson(testClassObject);
ArrayList<JSONObject> arrayList = new ArrayList<JSONObject>();
JSONObject postedJSON = new JSONObject();
try {
objJSON.put("key", "value");
// add key value for json formati
} catch (JSONException e) {
e.printStackTrace();
}
arrayList.add(postedJSON);
String variable = arrayList.toString();
Send the string to the server
Learn REST API for POST Sending HTTP POST Request In Java Reference post: Ferrybig answer