我创建了一个非常简单的JSON API。它具有3个属性,我可以访问和使用它们的值,因为创建了它并且知道它的属性是什么。但是,如果我使用的API我不知道它具有什么属性,那么我想说,控制台记录它们'我如何遍历API密钥?
这是我的API:
{
"datum1" : [{
"year": 2005,
"income": 23.5,
"expenses": 18.1,
"id":0
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8,
"id":1
}, {
"year": 2007,
"income": 30.1,
"expenses": 23.9,
"id":2
}, {
"year": 2008,
"income": 29.5,
"expenses": 25.1,
"id":3
}, {
"year": 2009,
"income": 24.6,
"expenses": 24.6,
"id":4
}],
"datum2" :[{
"year": 2005,
"income": 33.5,
"expenses": 38.1,
"id":0
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8,
"id":1
}, {
"year": 2007,
"income": 24.1,
"expenses": 17.9,
"id":2
}, {
"year": 2008,
"income": 23.5,
"expenses": 27.1,
"id":3
}, {
"year": 2009,
"income": 28.6,
"expenses": 24.3,
"id":4
}],
"brands":["Hinata","Indra","Tobi","Guy"]
}
我正在使用json服务器为其提供服务,并从我的角度应用程序中使用它。
我如何在控制台中打印的不是键值(datum1,datum2,brand),而是键本身?
我对for in
执行了get请求后,尝试执行for of
和https://localhost:3000
,希望我能得到整个JSON API,然后能够console.log键,但我得到404。
我希望有人能理解这篇凌乱的帖子并给我一些线索。。谢谢。
答案 0 :(得分:1)
var data={
"datum1" : [{
"year": 2005,
"income": 23.5,
"expenses": 18.1,
"id":0
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8,
"id":1
}, {
"year": 2007,
"income": 30.1,
"expenses": 23.9,
"id":2
}, {
"year": 2008,
"income": 29.5,
"expenses": 25.1,
"id":3
}, {
"year": 2009,
"income": 24.6,
"expenses": 24.6,
"id":4
}],
"datum2" :[{
"year": 2005,
"income": 33.5,
"expenses": 38.1,
"id":0
}, {
"year": 2006,
"income": 26.2,
"expenses": 22.8,
"id":1
}, {
"year": 2007,
"income": 24.1,
"expenses": 17.9,
"id":2
}, {
"year": 2008,
"income": 23.5,
"expenses": 27.1,
"id":3
}, {
"year": 2009,
"income": 28.6,
"expenses": 24.3,
"id":4
}],
"brands":["Hinata","Indra","Tobi","Guy"]
};
Object.keys(data).forEach(k=>{
console.log(k)
})
答案 1 :(得分:1)
如果为此创建一个模型并将其映射到than。比访问键和值容易 https://jvilk.com/MakeTypes/ 这是一个从json生成模型的好网站
答案 2 :(得分:1)
似乎您正在尝试仅使用域名枚举所有API端点。
就像您要向https://localhost:3000
发出请求一样,它应该返回服务器中所有可用API端点的列表。在这种情况下,它将不可用(除非配置了特定的API端点来执行此操作)。如果您使用的是第三方API,则通常会有包含所有可用端点和请求方法的文档。