Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

edoc's avatar
Level 24

JSON.stringify for array of objects

This is a noobish question. When sending a post request using Vue resource .You send data like this when sending a single item

submit:function(){
                var customizedExercises = this.customizedExercises;
                this.$http.post('/api/customized-exercises', customizedExercises).then(function(response){
                    console.log(response);
                    }
            },

But, when sending an array of objects you have to do

submit:function(){
                var customizedExercises = JSON.stringify(this.customizedExercises);
                this.$http.post('/api/customized-exercises', customizedExercises).then(function(response){
                    console.log(response);
                    }
                })
            },

data

customizedExercises : [{ weight:'',sets_duration:'',name:'',reps:'',exercise_day_id:'' }]

Why does only an array need to be mutated?

0 likes
2 replies
spekkionu's avatar
Level 48

This actually has to do with http itself rather than any individual javascript library.

When an object is passed as the data parameter the POST request is sent as "application/x-www-form-urlencoded"

The object is serialized as a sting and sent as the request body.

For example the object {name: "Bob Smith", age: 42} would be sent with the request body name=Bob+Smith&age=42

When an array or other more complex object (IE with other nested objects in it) is provided the request is sent as "application/json" and the request body is sent as a json string.

One major difference you might not notice because Laravel handles it for you is that when sent as a "application/x-www-form-urlencoded" request the parameters are all available in the $_POST superglobal but with a json request you need to manually parse the request body using something like file_get_contents('php://input') or fopen('php://input', 'r'). This is a bit of a pain so it is nice that Laravel (and pretty much any other http request library or framework) abstracts this away and lets you access the data that same way.

3 likes
edoc's avatar
Level 24

thanks for explaining it

Please or to participate in this conversation.