我有以下示例JSON,我想获得像Dribbble,Behance这样的列的名称......
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
callback(body)
var json = body.result;
for (var key in json) {
if (json.hasOwnProperty(key)) {
var column = Object.keys(key);
console.log(column[0]);
}
}
}
})
我正在使用Request模块,它返回JSON很好,但我很难以字符串格式获取列名。如果我至少可以获得数字格式的列,我将能够知道它是否是正确的列,但我得到的是两个0。
{{1}}
答案 0 :(得分:2)
var json = {
"status": 200,
"success": true,
"result": [
{
"Dribbble": 'a',
"Behance": '',
"Blog": 'http://blog.invisionapp.com/reimagine-web-design-process/',
"Youtube": '',
"Vimeo": ''
},
{
"Dribbble": '',
"Behance": '',
"Blog": 'http://creative.mailchimp.com/paint-drips/?_ga=1.32574201.612462484.1431430487',
"Youtube": '',
"Vimeo": '' }
]
}
// get the results (useful data) somewhere
var results = json["result"];
// get the first result set, or you can loop trhrough all, assuming that each reuslt set is the same.
if (results.length > 0){
var columnsIn = results[0];
for(var key in columnsIn){
console.log(key); // here is your column name you are looking for
}
}else{
console.log("No columns");
}
此代码段应指向正确的方向
答案 1 :(得分:2)
关闭Chad Peruggia的代码,你可以通过这样做打印出结果数组中的每个键值对:
var json = {
"status": 200,
"success": true,
"result": [
{
"Dribbble": 'a',
"Behance": '',
"Blog": 'http://blog.invisionapp.com/reimagine-web-design-process/',
"Youtube": '',
"Vimeo": ''
},
{
"Dribbble": '',
"Behance": '',
"Blog": 'http://creative.mailchimp.com/paint-drips/?_ga=1.32574201.612462484.1431430487',
"Youtube": '',
"Vimeo": '' }
]
}
// get the results (useful data) somewhere
var results = json["result"];
// you can loop through all, assuming that each result set is the same.
if (results.length > 0) {
// iterating through the results array
for(var i = 0; i < results.length; i++) {
// get i-th object in the results array
var columnsIn = results[i];
// loop through every key in the object
for(var key in columnsIn){
console.log(key + ' : ' + results[i][key]); // here is your column name you are looking for + its value
}
}
}
else {
console.log("No columns");
}