Why do I get square brackets when trying to convert array to JSON string using stringify

Aerial

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);
        }

    }
Halcyon

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 = {};

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

JSON.stringify(array) surrounded with square brackets

convert string with square brackets to array or list in Javascript

trying to convert string of letters and square brackets into a list of letters and lists

I get the error "TypeError: list indices must be integers or slices, not str" when trying to request something that is in square brackets

Why do I get “Cannot implicitly convert type 'int' to User” when trying to insert an INT in FOREIGN KEY using EF Core?

Why is JavaScript adding extra square brackets when I push a sub array into another array?

How do I convert square brackets to curly bracket in text using by regular expression?

How do i make a string from an array, saving all the square brackets

Array data is shown with square brackets when parsing data from a JSON file using Gson in Android

Why do I get an incorrect result when trying to convert from Hex to Dec in Haskell?

Convert string with index in brackets to JSON array

converting a normal string into a json array by including square brackets and double qoutes

get key from JSON string with square brackets php

Why to use square brackets [ ] when using custom hook

How do I replace string containing square brackets

How do I get the value without the square brackets

How do I get rid of the square brackets after the code is implemented?

Why am I getting "no implicit conversion of String into Integer" when trying to get Nested JSON attribute?

Why do I get "Undefined variable" when trying to resolve a multi-dimensional array?

Why are square brackets needed to stringify all elements of a Map in Javascript?

Why do I always get a "trailing characters" error when trying to parse data with serde_json?

Why do I get TypeError when trying to do dot product?

Error when trying to convert Java object to JSON string using GSON

Why do I get a "the location is not a folder" error when trying to open files using Dash or Synapse?

Why do I get a segmentation fault when trying to create a linked list using structures?

Why do I get a green image when I convert an RGB image to grayscale using OpenCV?

How do I output a javascript array where each array item is a new line using JSON.stringify

Convert array to object wrapped with square brackets [ ]

get string when trying to make a dynamic json list / array