Kristo
Kristo

Reputation: 1367

Reading simple JSON Object returns undefined

I have a JSON object which looks like this.

  {
  "Manager": "[{\"firstname\":\"Kris\"}],[{\"lastname\":\"test\"}]",
  "Employee": "[{\"firstname\":\"Nick\"}],[{\"lastname\":\"test\"}]"
  }

I am using Jquery to try and read my object but it seems that I am doing a mistake somehow.

JSON.stringify(data[0].Manager.firstname) //returns undefined.

Any suggestions on how to read this via JQuery will be much appreciated

Please note my datatype is JSON on my ajax call. Thanks in advance.

Upvotes: 0

Views: 186

Answers (3)

Farhad Bagherlo
Farhad Bagherlo

Reputation: 6699

this is not valid json "[{\"fistname\":\"Nick\"}],[{\"lastname\":\"test\"}]"

is valid json "[{\"fistname\":\"Nick\"},{\"lastname\":\"test\"}]"

chack json online

var obj= {"Manager": "[{\"fistname\":\"Kris\"},{\"lastname\":\"test\"}]","Employee": "[{\"fistname\":\"Nick\"},{\"lastname\":\"test\"}]"};
  $.each(obj,function(key,value){
    if(key=='Manager'){
       var elem=$.parseJSON(value);
       $.each(elem,function(key,value){
         if(!(typeof value.fistname === "undefined"))
            console.log(value.fistname);
       });
     }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Dalin Huang
Dalin Huang

Reputation: 11342

This is how you do json with js.

var data = [{
    "Manager": {
      "firstname": "Kris",
      "lastname": "test"
    },
    "Employee": {
      "firstname": "Nick",
      "lastname": "test"
    }
  },
  {
    "Manager": {
      "firstname": "Kris2222",
      "lastname": "test222"
    },
    "Employee": {
      "firstname": "Nick222",
      "lastname": "test2222"
    }
  }
];



console.log(data[0].Manager.firstname);
console.log(data[1].Manager.firstname);

Upvotes: 0

Skye MacMaster
Skye MacMaster

Reputation: 914

Your json has fistName for the firstName. Changing it to firstName should fix it.

Upvotes: 0

Related Questions