Invalid JSON.stringify (object)

Sorry my last question was so confusing, I confused myself, but now I have the right example:

var obj = {};
obj.entities = [];
obj.entities["player"] = [];
obj.entities["player"]["0"] = [];
obj.entities["player"]["0"]["pos"] = "0,0";

var jsonStr = JSON.stringify(jsonObj);

// {"entities":[]}
console.log(JSON.stringify(obj));

The conclusion is JSON.stringify(obj)incorrect, as you can see. What causes this?

+5
source share
6 answers

First you create an array ( []), and then assign properties to it using non-numeric keys ( player). This is technically possible (as in the case of an error), but not for any arrays.

You should use objects ( {}) instead . Also ["player"]matched with .player.

var obj = {};
obj.entities = {};
obj.entities.player = []; // array here because you're filling with indices ([0])
obj.entities.player[0] = {}; // object again, because non-indices as keys (`pos`)
obj.entities.player[0].pos = "0,0";

Objects can accept any property key. Arrays are a subset of objects that should only have indexes (numbers >= 0).

+12

, JSON, :

var obj = {
  'entities': [
    {'player':{'pos': '0,0'}}
  ]
};
+3

indeces / .

var obj = {};
obj.entities = {};
obj.entities["player"] = {};
obj.entities["player"]["0"] = [];
obj.entities["player"]["pos"] = "0,0";

// {"entities":{"player":{"0":[],"pos":"0,0"}}}
console.log(JSON.stringify(obj));
+1

entities, entities["player"] entities["player"]["0"] , .

, . .

:

var obj = {};
obj.entities = {};   //  <------------ this is an object now
obj.entities["player"] = {};    // <--------- also an object
obj.entities["player"]["0"] = {};   // <-------- and so on
obj.entities["player"]["0"]["pos"] = "0,0";
+1

, javascript. ([]) . :

obj.entities = [];
obj.entities["player"] = [];

, obj.entities , player . player . . , . :

obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = 'foo bar';
+1

You confuse objects with arrays. The following code will work.

var obj = {};
obj.entities = {};
obj.entities.player = [];
obj.entities.player[0] = {};
obj.entities.player[0].pos = "0,0";

What you went wrong:

  • An array can have only integer indices. Therefore, it is incorrectly spelled ["1"] if you intend to use it aas an array.
  • To properly serialize, only an object can have named properties, such as object.entities.playeror object.entities["player"].
+1
source

All Articles