0

Using JavaScript; how do I produce this output

cell
work (123) 456 7890

from this valid json

{"phone": [
{
    "@attributes": {
        "type": "cell",
        "ext": ""
    }
}, "(123) 456 7890", {
    "@attributes": {
        "type": "work",
        "ext": ""
    }
}
]}
9
  • Who created that abomination of a JSON document? It should be [{"type": "cell"}, {"type": "work", "number":"(123) 456 7890"}]. This looks to be automatically generated from an XML document. If that's the case, you should parse that XML instead. Commented Aug 26, 2011 at 10:30
  • @phihag php json_encode from <phone type="cell" ext=""></phone> <phone type="work" ext="">(123) 456 7890</phone> Commented Aug 26, 2011 at 10:35
  • @thilo everything.. cant access that phone number Commented Aug 26, 2011 at 10:36
  • json.org/js.html ... phone is an array. You want to access the second element. I don't see where the problem could be? Commented Aug 26, 2011 at 10:36
  • Actually, it looks like it might be VCard data that's been converted to XML and then to JSON… if so, yaiks Commented Aug 26, 2011 at 10:37

2 Answers 2

1

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

var jsonObj = JSON.parse(jsonString);

var type = 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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

sorry about the dupe, trying to get my head around the problem. thanks tho!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.