简体   繁体   中英

how to access the nested json element?

contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"}

this is particular data is part of a bigger json data. I am accessing it via JSONArrayName.contact1. How do i access name, relation and number now?

var obj, dbParam, xmlhttp, myObj, x, txt = "";  
obj = { "table":"Successful", "limit":20 };
dbParam = JSON.stringify(obj); 
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    myObj = JSON.parse(xmlhttp.responseText);
    console.log(myObj);
    //console.log(myObj[0]);
    document.getElementById("userId").innerHTML = myObj.id;
    document.getElementById("DOB").innerHTML = myObj.dob;
    document.getElementById("bloodGroup").innerHTML = myObj.bloodGroup;
    document.getElementById("aadhar").innerHTML = myObj.aadharCard;
    document.getElementById("allergies").innerHTML = myObj.allergies;
    document.getElementById("insurances").innerHTML = 
    myObj.insuranceDetails;
    var contact1 = myObj.contact1;
    console.log(contact1);

}

console output: myobj:

{id: "123456", insuranceDetails: null, allergies: null, bloodGroup: "A", gender: "Female", contact1: {name: "Kesh", relation: "Mother", number: "9819269972"}, contact2: {name: "Kesh", relation: "Mother", number: "9819269972"}}

contact1:

{name: "Kesh", relation: "Mother", number: "9819269972"}

Use Dot-Notation to access the value corresponding to keys in the object.

 var JSONArrayName = {contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"}}; console.log(JSONArrayName.contact1.name); console.log(JSONArrayName.contact1.relation); 

You can access them by using dot notation like

var data = { contact1 : {name: "Kesh", relation: "Mother", number: "9819269972"} } 
console.log(data.contact1.name);
console.log(data.contact1.relation);
console.log(data.contact1.number);

can access the data in such a way:

myObj.contact[0].name

In my console it work fine, make sure that you have a non empty variable myObj 安慰

It works properly.

在此处输入图片说明

myObj.contact1.name
myObj.contact1.relation
myObj.contact1.number

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