Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Stringify Removing Data From Object

I am working on sending JSON, via jQuery ajax, to a Node server. My jQuery ajax is working. See below.

var user = JSON.stringify(userObject);
$.ajax({
        type: 'POST',
        url: 'http://localhost:5000/save',
        contentType: 'application/json',
        dataType: 'json',
        data: user
    })
    .done(function(data) {
        console.log(data.link, 'here is the link');
        callback(data.link);
    })
    .fail(function(err) {
        console.log(err);
        callback(err);
    });

My issue is that when I console log user, a json object that has been stringified, I have information inside arrays that are being lost. The part of the object I am losing looks like this.

Losing this part

And it is showing up stringified in the console like this:

stringified console log

The information that is stored inside of those arrays inside of the parent user object are not being stored. Any suggestion to why this might be will help. If you have any alternative methods that I can use to send this data structure via jQuery ajax, please let me know.

Edit Here is where regions is created:

// Add regions to the bracket layout object
        user.regions = [];
        for (var a = 0; a < 2; a++) {
            user.regions[a] = [];
            user.regions[a].columns = [];
        }

Thanks,

like image 785
Max Baldwin Avatar asked Jan 15 '15 00:01

Max Baldwin


People also ask

What does JSON Stringify do to an object?

The JSON. stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Does JSON Stringify remove methods?

stringify() method not only stringifies an object but also removes any function if found inside that object.

How do I hide something in JSON?

To hide, remove or omit certain values from the output of the JSON. stringify() method, we can pass a replacer function as a second argument to the method in JavaScript.

Is it bad to use JSON Stringify?

It`s ok to use it with some primitives like Numbers, Strings or Booleans. As you can see, you can just lose unsupported some data when copying your object in such a way. Moreover, JavaScript won`t even warn you about that, because calling JSON. stringify() with such data types does not throw any error.


Video Answer


1 Answers

Well, the problem is that you're creating AN ARRAY then continue working with it as with an object.

Use

user.regions[a] = {};

instead.

What happens is that JSON.stringify sees there is an array, tries to iterate over its numeric indexes which it does not have so it results in an empty array.

Example on JSFiddle: http://jsfiddle.net/Le80jdsj/

like image 142
zerkms Avatar answered Oct 01 '22 05:10

zerkms