stuntboots
stuntboots

Reputation: 81

Arrays in AJAX request JSON object data

I am sending a request to a Node/Express server using jQuery thats data is a JSON object containing an array:

var data = {
    "name": "James Jamesy",
    "children": [
        {
            "name": "Tiny James",
            "age": "4"
        },
        {
            "name": "Little James",
            "age": "6"
        },
        {
            "name": "Graham",
            "age": "8"
        }
    ]
}

var request = $.ajax({
    method: 'PUT',
    url: apiPath + 'updateuser',
    data: data,
    dataType: 'json'
});

The request itself is working fine, however the server is reporting the data as:

{ 
    name: 'James Jamesy',
    'children[0][name]': 'Little James',
    'children[0][age]': '4',
    'children[1][name]': 'Medium James',
    'children[1][age]': '6',
    'children[2][name]': 'Graham',
    'children[2][age]': '8'
}

Now I've figured out that I can get my desired result by instead stringifying the children array:

var data = {
    "name": "James Jamesy",
    "children": JSON.stringify([ ... ])
}

And then JSON.parse()ing it on the server.

However I am hoping someone can explain why the array is converted as it is in the request, and whether I should be handling this a different way? As in this instance converting the single array is fine, but going forward I might have semi-complex objects I'm looking to send to the server.

Thanks in advance!

EDIT: Additionally and strangely(?), if I send the JSON result back as the passed JSON, it works perfectly:

res.json(JSON.parse(req.body.categories));

The browser logs out the object and I can manipulate it perfectly fine.

Upvotes: 1

Views: 2369

Answers (1)

Luis Estevez
Luis Estevez

Reputation: 1417

You weren't passing a JSON string through ajax which is why you couldn't handle the data on the back end.

var data = {
    "name": "James Jamesy",
    "children": [
        {
            "name": "Tiny James",
            "age": "4"
        },
        {
            "name": "Little James",
            "age": "6"
        },
        {
            "name": "Graham",
            "age": "8"
        }
    ]
}

var request = $.ajax({
    method: 'PUT',
    url: apiPath + 'updateuser',
    data: JSON.stringify(data),
    contentType: 'application/json', // for request
    dataType: 'json' // for response
});

Upvotes: 1

Related Questions