Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

JSON nested object post to node.js server?

JSON nested object post to node.js server?

Problem

I want to POST an Object via Json to node.js server.

The Object structure is nested, and never succeeded to receive and parse correctly on node.js server site.


EDIT2

I found a solution: see the answer section...


EDIT

I found

     console.log(body);

itself output

val1=hello&val2%5Bval3%5D=world

//= {"val1":"hello","val2[val3]":"world"}

weired JSON way


client.js

    var data ={val1:"hello",val2:{val3:"world"}};
    console.log(data); // -> *1
    $.ajax({
        url:"/",
        type:"POST",
        dataType: 'json',
        data:data,
        success:function (res)
        {
            resHandler(res);
        }
    });

*1 ChromeDevelopersTool

Object

val1: "hello"

val2: Object

val3: "world"


server.js

var onreq = function (req, res)
{
    if(req.method == 'POST')
    {
        var body = '';
        req.on('data', function (data)
        {
            body += data;
        });
        req.on('end', function ()
        {
            var json = qs.parse(body);
            console.log(json.val1); //hello
            console.log(json.val2); //undefined
            console.log(json.val3); //undefined

            console.log(JSON.stringify(json)); 
            //{"val1":"hello","val2[val3]":"world"}
        });
    }

I understand

val2[val3] is val2.val3

However,


Problem 1

JSON.stringify prints out

{"val1":"hello","val2[val3]":"world"}

not

{val1:"hello",val2:{val3:"world"}}

It's ugly, and I don't know why it's like that.


Problem 2

I can never get {val3:"world"}

console.log(json.val3); //undefined


Anyone can explain, and how can I POST a nested JSON to node.js server?

Thanks.

Problem courtesy of: Ken OKABE

Solution

Do NOT use JSON typed data on jQuery Ajax, instead use Stringified JSON

I created a WIKI

http://code.google.com/p/kenokabe/wiki/nestedJSONproblem

Solution courtesy of: Ken OKABE

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

JSON nested object post to node.js server?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×