我有一个Chrome扩展程序,用于从外部网址获取JSON数据,然后在控制台中输出结果。
我的外部JSON文件如下所示:
{
"success": true,
"reason": "test",
"stats": {
"number_of_items": "",
"recently_updated": 0
},
"catalog_items": [
[5207053, "White Witch Hat", "1,000", 1869],
[31149956, "Hot Pink Faberg\u00e9 Egg", "800", 1409]
]
}
我想显示"catalog_items"
中的所有对象。通过使用下面的代码,它在控制台中输出:
$.getJSON('https://example.com', function(data) {
console.log(data)
});
-
{success: true, reason: "test", stats: {…}, catalog_items: Array(15)}
catalog_items
:
(15) [Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4), Array(4)]
reason
:
"test"
stats
:
{number_of_items: "", recently_updated: 0}
success
:
true
__proto__
:
Object
然而,这不是我想要的。我希望它显示:
ID: 5207053 Title: White Witch Hat Price: 1,000 RAP: 1869
ID: 31149956 Title: Hot Pink Faberg\u00e9 Egg Price: 800 RAP: 1409
答案 0 :(得分:0)
您需要遍历catalog_items
并将数据连接到这样的字符串:
$.getJSON('https://example.com', function(data) {
var catalog_items = data.catalog_items
for(var i=0;i<catalog_items.length;i++){
var item = catalog_items[i]
var line = 'ID: '+item[0]
line += ' Title: '+item[1]
line += ' Price: '+item[2]
line += ' RAP: '+item[3]
console.log(line)
}
});
要仅显示新条目,您需要跟踪ID。
var shown_products = []
$.getJSON('https://example.com', function(data) {
var catalog_items = data.catalog_items
for(var i=0;i<catalog_items.length;i++){
var item = catalog_items[i]
if(shown_products.indexOf(item[0])!=-1) // product already shown
continue
var line = 'ID: '+item[0]
line += ' Title: '+item[1]
line += ' Price: '+item[2]
line += ' RAP: '+item[2]
console.log(line)
shown_products.push(item[0])
}
});
答案 1 :(得分:0)
上面有很多有用的答案,这个答案使用console.table
// console.table polyfill
if (!console.table) {
console.table = function(arr) {
var keys = Object.keys(arr[0]);
var horizontalLine = '\r\n' + '-'.repeat(8 * keys.length) + '\r\n';
var heading = Object.keys(arr[0]).join('\t');
var str = horizontalLine;
str += heading;
arr.forEach(function(obj) {
str += horizontalLine + Object.values(obj).join('\t\t');
});
str += horizontalLine;
console.log('%c' + str, 'font-family: monospace');
};
}
// your response data
var data = {
"success": true,
"reason": "test",
"stats": {
"number_of_items": "",
"recently_updated": 0
},
"catalog_items": [
[5207053, "White Witch Hat", "1,000", 1869],
[31149956, "Hot Pink Faberg\u00e9 Egg", "800", 1409]
]
}
// simple class
function Item(values) {
this.id = values[0];
this.title = values[1];
this.price = values[2];
this.rap = values[3];
}
var items = data.catalog_items.map(function(next) {
return new Item(next);
});
console.table(items);
&#13;
请参阅演示按运行代码段并打开浏览器开发人员控制台