简体   繁体   English

如何访问嵌套的 json 元素?

[英]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.这是特定数据是更大 json 数据的一部分。 I am accessing it via JSONArrayName.contact1.我通过 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:控制台输出: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"}} {id:“123456”,保险详情:空,过敏:空,血型:“A”,性别:“女性”,联系人1:{姓名:“凯什”,关系:“母亲”,号码:“9819269972”},联系人2 :{姓名:“凯什”,关系:“母亲”,号码:“9819269972”}}

contact1:联系人1:

{name: "Kesh", relation: "Mother", number: "9819269972"} {名称:“凯什”,关系:“母亲”,编号:“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 您可以使用dot notation来访问它们,例如

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 myObj.contact [0] .name

In my console it work fine, make sure that you have a non empty variable myObj 在我的控制台中,它工作正常,请确保您有一个非空变量myObj 安慰

It works properly. 它正常工作。

在此处输入图片说明

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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