简体   繁体   English

从json提取值

[英]Extracting values from json

I'm having some trouble trying to figure out how to extract the name and url from this Json. 我在尝试弄清楚如何从此Json提取名称和URL时遇到麻烦。

Here's my Json and Javascript. 这是我的Json和Javascript。 This successfully loops through and extracts each object eg the "1977" portion. 这样可以成功遍历并提取每个对象,例如“ 1977”部分。 But I need to then extract the name and url and display them. 但是我需要提取名称和URL并显示它们。 Can anyone help? 有人可以帮忙吗? It's so simple I can barely believe I have to ask. 这是如此简单,我简直不敢相信我要问。

[{
    "1977": [{
        "name": "my name 1",
        "url": "myurl 1"
    }],
    "2104": [{
        "name": "my name 2",
        "url": "myurl 2"
    }]
}]

var obj = JSON.parse(jsonString); //a parses above json
for (var i = 0; i < obj.length; i++) { 
    console.log(obj[i]); //returns the object
}

You need to iterate over the objects and pick only the attributes needed, like this 您需要遍历对象并仅选择所需的属性,像这样

for (var i = 0; i < obj.length; i++) {
    for (var year in obj[i]) {
        console.log("Current year is", year);
        console.log(obj[i][year][0].name);
        console.log(obj[i][year][0].url);
    }
}

Output 产量

Current year is 1977
my name 1
myurl 1
Current year is 2104
my name 2
myurl 2
for (var i = 0; i < obj.length; i++) { 
   console.log(obj[i][0].name); 
   console.log(obj[i][0].url); 
} 

Here are two ways to access the name. 这是访问名称的两种方法。

obj[0]['1977'][0]['name']

obj[0]['1977'][0].name
for (var i = 0; i < obj.length; i++) {
    for (var j=0; j<obj[i].length; j++) {

        console.log(obj[i][j][0].name);
        console.log(obj[i][j][0].url);
    }
}

You can simply extract using dot operator 您可以简单地使用点运算符提取

for (var i = 0; i < obj.length; i++) {
    var og = obj[i];
    Object.keys(og).forEach(function (key) {  //missed to loop through it
        console.log(og[key][0].name);
        console.log(og[key][0].url);
    });

}

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

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