On the webpage I am POSTing some JSON using jQuery:
$.post('/url', data);
My data is a javascript object that contains some values and an array. JSON.stringify(data) looks like:
{"favoriteAnimal":"piglet", "okayAnimals":["cats","dogs"]}
I'm consuming this JSON in a NodeJS webapp using ExpressJS (which is wired up with the body-parser middleware). I can retrieve the favorite animal like req.body.favoriteAnimal and it gives me the string piglet which is all fine and dandy.
But how do I access the values in the array?
req.body.favoriteAnimal // piglet
req.body.okayAnimals // undefined
req.body.okayAnimals[] // syntax error
This works...
req.body['okayAnimals[]']
...but smells fishy. It also won't return an array if the original data that is being POSTed contains only one element in its array (it just returns a single string).
Is there something going on with the the jQuery encoding of the JSON or something going on with the decoding in ExpressJS that's preventing me from accessing it like req.body.okayAnimals and getting an array every time?
req.body.okayAnimalsshouldn't beundefinedgiven that json string.datais json (a string) and not an object? As a matter of fact, i'm positive it's an object and not a string, because that explains the behavior you are seeing. It gets turned into form parameters if it's an object:favoriteAnimal=piglet&okayAnimals[]=cats&okayAnimals[]=dogstypeof(data)returns anobjectso you are correct, it is not a string