Pregunta

When I try to convert the array below to a string using JSON.stringify, I get to see empty square brackets only. I tried console.log to debug, but I do see the data I want to convert into a string, so what am I doing wrong here? Any help will be much appreciated!

function jsonSuccess( data ){

        var jsonArr = new Array();

        for( var i = 0; i < data.length; i++ ){
            var shipInfo = new Array();
            var shipRows = new Array();

            $.each( data[i], function( key, value ){


                if ( key == "EniNumber" ) {
                    shipInfo['E'] = value;
                    //console.log( shipInfo.E );
                }

                if ( key == "Name" ) {
                    shipInfo['N'] = value;
                }

                if ( key == "StartDate" ) {
                    shipInfo['S'] = value;
                }

                if ( key == "Rows" ) {

                    $.each( value, function( subKey, subValue ){

                        var rowContent = {
                            "T": subValue.T,
                            "X": subValue.X,
                            "Y": subValue.Y,
                            "D": subValue.D
                        }

                        shipRows.push( rowContent );

                    });

                    shipInfo['R'] = shipRows;
                }

            });


            jsonArr[i] = shipInfo;

            var myJsonString = JSON.stringify(jsonArr);
            console.log(myJsonString);
        }

    }
¿Fue útil?

Solución

You are using an Array as an object.

In Javascript you have Arrays and objects. But as you may know Arrays are also objects and this has some weird implications.

var arr = [];
arr[0] = "foo"; // this is fine
console.log(JSON.stringify(arr)); // [ "foo" ]
arr.length; // 1 ok

But since an Array is an object, we can also assign properties:

arr.foo = "bar";
console.log(arr); // [ 0: "foo", foo: "bar" ]
console.log(JSON.stringify(arr)); // [ "foo" ] .. where did bar go?
arr.length; // 1 huh?

We're mixing array values and object properties.

The JSON encoder looks at the object and sees that it's an (instanceof) Array and serializes it. It looks at arr.length (which is 1 in the example) so you get just [ "foo" ]. The properties on the array are ignored.


It's important to realize the difference between array valus and object properties. Arrays in JavaScript are never associative. If you set a property on an Array it wont increase the length and it wont show up if you loop over it in a for-loop.


Change:

var shipInfo = new Array();

To:

var shipInfo = {};

Otros consejos

shipInfo is not an array, it is an object so try var shipInfo = {};

Demo: Problem, Solution

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top