如何访问以下JSON数据中的每个元素?

时间:2014-11-11 10:02:57

标签: javascript json

"email": "FamilyMembers: 54; Children: 4; Income: 8484; Literacy: UG; MaritalStatus: Married; 

我正在尝试此代码

if (arr.email != undefined) {
         out += "Family Members:" + arr.email.FamilyMembers + "<br/>Children:" + arr.email.Children + "<br/>Income:" + arr.email.Income + "<br/>Literacy:" + arr.email.Literacy + "<br/>Marital Status:" + arr.email.MaritalStatus; 

    }

3 个答案:

答案 0 :(得分:1)

您的JSON似乎格式不正确。如果您确实希望以对象的形式访问电子邮件的子元素,那么您的JSON应如下所示:

 { "email" : { "FamilyMembers": 54,
            "Children": 4, 
            "Income": 8484, 
            "Literacy": "UG",
            "MaritalStatus": "Married"
          }
  }

答案 1 :(得分:0)

以下代码就足够了。

var p = {"email": "FamilyMembers: 54; Children: 4; Income: 8484; Literacy: UG; MaritalStatus: Married;"}

for (var key in p) {
  if (key == email) {
  var emailElt = p[key]
  for (var subKey in emailElt) {
      if (p.hasOwnProperty(subKey)) {
         alert(subKey + " -> " + emailElt[subKey]);
      }
    }
  }
}

答案 2 :(得分:0)

解析它,例如:

var myString = arr.email;
var arrayOfKV = myString.split(";");
var obj = {};
while( elem = arrayOfKV.shift() ) {
  var kV = elem.split(":");
  obj[k] = V;
}


var properJSON = JSON.stringify({ email: obj });