Skip to content Skip to sidebar Skip to footer

Javascript Json Values

Using JavaScript; how do I produce this output cell work (123) 456 7890 from this valid json {'phone': [ { '@attributes': { 'type': 'cell', 'ext': '' } },

Solution 1:

In a very narrow sense, you'd need to do this

var jsonObj = JSON.parse(jsonString);

vartype = jsonObj.phone[0]['@attributes'].type// "cell"var phoneNumber = jsonObj.phone[1] // "(123) 456 7890"

But the structure of that JSON data may change, so you can't rely on the 0/1 indexes, and anyway the structure is weird. Like the comments say, if it comes from XML, then parse that instead

Solution 2:

I see you kind of duplicate question from: Access json value using JavaScript object notation Simple loop could help:

var tel;
for (var i=0,l=phone.length; i<l; i++) {
  if (phone[i]['@attributes']) {
    if (phone[i-1] && typeof phone[i-1]==='string') {
      tel = phone[i-1];
    } else {
      tel = '';
    }
    console.log(phone[i]['@attributes'].type+' '+tel);
  }

But the guys above are right, if the structure changed a bit, this code will probably won't work.

Post a Comment for "Javascript Json Values"