简体   繁体   中英

How to access each element in the following JSON data?

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

I am Trying this code

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; 

    }

Your JSON seems to be improperly formatted. If you do want to access the sub-elements of email as objects, your JSON should look like this:

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

Following code will be enough.

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]);
      }
    }
  }
}

parse it, for example :

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 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM