Search code examples
ajaxjsonobjectstringify

JSON.stringify() - nested objects


What's the proper way to use JSON.stringify() on nested objects? I'm getting a bad request from a api call that expects a JSON string:

testData = {"credentials": {"user": "test@email.com", "password": "testpassword", "country": "us"}};

when I view the postDasta:

"{"credentials": {"user": "test@email.com", "password": "testpassword", "country": "us"}}";

$.ajax({
    ...
    data: JSON.stringify(testData),
    ...
});

Thanks,

J


Solution

  • The answer I was looking for was: You need to use JSON.stringify to first serialize your object to JSON, and then specify the content-type so your server understands it's JSON.

    So, contentType and stringify are necessary if the server is expecting JSON.