Thursday 15 July 2010

javascript - Consuming JSON with an array in ExpressJS -



javascript - Consuming JSON with an array in ExpressJS -

on webpage posting json using jquery:

$.post('/url', data);

my info javascript object contains values , array. json.stringify(data) looks like:

{"favoriteanimal":"piglet", "okayanimals":["cats","dogs"]}

i'm consuming json in nodejs webapp using expressjs (which wired body-parser middleware). can retrieve favorite animal req.body.favoriteanimal , gives me string piglet fine , dandy.

but how access values in array?

req.body.favoriteanimal // piglet req.body.okayanimals // undefined req.body.okayanimals[] // syntax error

this works...

req.body['okayanimals[]']

...but smells fishy. won't homecoming array if original info beingness posted contains 1 element in array (it returns single string).

is there going on the jquery encoding of json or going on decoding in expressjs that's preventing me accessing req.body.okayanimals , getting array every time?

kevin's reply got me there.

$.post('/url', json.stringify(data)) send string 1 step closer. unfortunately jquery's $.post sets wrong header

content-type:application/x-www-form-urlencoded; charset=utf-8

which expressjs's body-parser not handle appropriately. end with

req.body={"{\"favoriteanimal\":\"piglet\",\"okayanimals\":[\"cats\",\"dogs\"]}":""}

i rewrote how sending data.

$.ajax({ url: '/url', type: 'post', data: data, contenttype: 'application/json; charset=utf-8', datatype: 'json' })

i saw browser sending right headers

content-type:application/json; charset=utf-8

and observed

req.body={"favoriteanimal":"piglet","okayanimals":["cats","dogs"]}

javascript jquery node.js express

No comments:

Post a Comment