-1

this is simple code which i want to parse values json array and print data from that,

var data = {
    "mobileNumber": "3",
    "userContacts": {
        "values": [{
            "nameValuePairs": {
                "contactName": "aaaaa",
                "contactPhone": "111111"
            }
        }, {
            "nameValuePairs": {
                "contactName": "bbbbb",
                "contactPhone": "222222"
            }
        }]
    }
};

var jsonArray = JSON.parse(data.userContacts.values);

for (var i=0; i<jsonArray['values'].length; i++){

    //print contactName and contactPhone from nameValuePairs

}

i created this link on jsFiddle to test that

mahdi pishguy
  • 994
  • 1
  • 14
  • 43

3 Answers3

2

You dont have to use JSON.parse. You already have a JSON.

You can just loop over what you need.

for (var i=0; i<data.userContacts.values.length; i++){
    console.log(data.userContacts.values[i].nameValuePairs.contactName,
                data.userContacts.values[i].nameValuePairs.contactPhone)
}

https://jsfiddle.net/ffv4grk7/

Also, read this for more info on how JSON.parse works.

Community
  • 1
  • 1
Aᴍɪʀ
  • 7,623
  • 3
  • 38
  • 52
  • 1
    And you were actually having a loop over the array `data.userContacts.values.values`, which does not exist. – nicovank Nov 01 '16 at 17:24
0

Or just :

data.userContacts.values.forEach(x => {
  console.log(x.nameValuePairs.contactName, x.nameValuePairs.contactPhone);
});
// aaaaa 111111
// bbbbb 222222
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
-1

Use this code you will get name and email

 for(i in data.userContacts.values) {
   x+=data.userContacts.values[i].nameValuePairs.contactName+"<BR>";
   x+=data.userContacts.values[i].nameValuePairs.contactPhone+"<BR>"; }
   document.getElementById("r").innerHTML = x;
Bugs
  • 4,491
  • 9
  • 32
  • 41