打印JSON属性

时间:2015-03-26 02:01:53

标签: javascript json

我目前正在尝试发送有关我从API收到的JSON对象的用户信息。格式的一个例子是

[
{
    "lang_code":        "eng",
    "site_language":    "1",
    "name":         "English"
},
{
    "lang_code":        "afr",
    "site_language":    "1",
    "name":         "Afrikaans"
},
{
    "lang_code":        "ale",
    "site_language":    "0",
    "name":         "Aleut"
},
]

我希望能够访问每种语言的lang_code属性并发送它。我试过用

var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
    languageCodes = languageResult[codes];
}

Object.keys什么都不做,因为它只向我发送了72个号码。有什么想法吗?

另一方面,我也希望人们能够键入“!languages [my command] eng ”,然后发送“English”而不是发送“1 is is [object Object]“。

2 个答案:

答案 0 :(得分:1)

假设body是你问题顶部的数组,如果你只想要一个包含所有语言代码的数组,那就足够了

var languageCodes = body.map(function(lang) {
    return lang.lang_code;
});



var body = [{
  "lang_code": "eng",
  "site_language": "1",
  "name": "English"
}, {
  "lang_code": "afr",
  "site_language": "1",
  "name": "Afrikaans"
}, {
  "lang_code": "ale",
  "site_language": "0",
  "name": "Aleut"
}];

var languageCodes = body.map(function(lang) {
  return lang.lang_code;
});

document.getElementById('out').innerHTML = JSON.stringify(languageCodes);

<pre id="out"></pre>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

我循环使用你的lang_codes:

var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];

for(var i = 0; i < codes.length; i++) {
    console.log(codes[i].lang_code);
}