0

My node app receives this json:

{ 
"team":"Man UTD"
,"playersAndRoles":
    {
        "Pogba":["Midfielder"]
        ,"Martial":["Striker","Wing"]
        ,"Ibrahimovic":["Striker"]
    }
}

Now, I read this json with this code:

var jsonBody = req.body;
console.log('jsonBody.playersAndRoles.length',    jsonBody.playersAndRoles.length);

However, the length is undefined. The JSON is valid. But Im not sure if the way the json represents array is correct. I can modify the JSON. If it is written in wrong way.

But the received JSON seems OK. because I can do this:

console.log('jsonBody.team', jsonBody.team); //Prints Man UTD

So I guess the wrong part is the definition of the "playersAndRoles" object. Is that correct?

PS: If I try to run a:

JSON.parse(jsonBody.playersAndRoles);

then it throws an exeption.

Emran
  • 188
  • 1
  • 12
oderfla
  • 1,695
  • 4
  • 24
  • 49

1 Answers1

0

jsonBody.playersAndRole Is not a array. jsonBody.playersAndRole is object. So if you want to make playerAndRole as a array you have to make json like this.

{
   "team":"Man UTD",
   "playersAndRoles":[
      {
         "Pogba":[
            "Midfielder"
         ]
      },
      {
         "Martial":[
            "Striker",
            "Wing"
         ]
      },
      {
         "Ibrahimovic":[
            "Striker"
         ]
      }
   ]
}
Emran
  • 188
  • 1
  • 12
  • Surely, separating the original object into three separate objects where the players' names are the property names isn't the best way to restructure that JSON (assuming that OP even has the option of changing the structure)? – JLRishe Feb 24 '17 at 11:26
  • 1
    You can find you object length without change you object. See hear for how http://stackoverflow.com/questions/5223/length-of-a-javascript-object – Emran Feb 24 '17 at 11:41