我今天写信给社区,因为我在尝试访问API提供的对象时遇到了一些困惑。
使用的API:
概念
我在访问API时会收到与myObject相同的对象,但要确保我们了解了我可以在下面访问它的源代码。
具有漂亮格式的对象
{
"result": [{
"id": "e9a821b6379bd22539226a4cc6956144",
"mode": "challenge",
"allowed_modes": ["block", "challenge", "whitelist", "js_challenge"],
"status": "active",
"notes": "BY API",
"scope": {
"id": "981969ce21909a61b62905c585ec9aaa",
"email": "user@example.com",
"type": "user"
},
"configuration": {
"value": "AD",
"target": "country"
},
"created_on": "2017-08-06T17:05:19.126546Z",
"modified_on": "2017-08-06T17:05:19.126546Z"
}],
"result_info": {
"page": 1,
"per_page": 1,
"total_pages": 251,
"count": 1,
"total_count": 251
},
"success": true,
"errors": [],
"messages": []
}
下面的代码会返回没有问题的数字251,这是预期的。
var myObject = {"result":[{"id":"e9a821b6379bd22539226a4cc6956144","mode":"challenge","allowed_modes":["block","challenge","whitelist","js_challenge"],"status":"active","notes":"BY API","scope":{"id":"981969ce21909a61b62905c585ec9aaa","email":"user@example.com","type":"user"},"configuration":{"value":"AD","target":"country"},"created_on":"2017-08-06T17:05:19.126546Z","modified_on":"2017-08-06T17:05:19.126546Z"}],"result_info":{"page":1,"per_page":1,"total_pages":251,"count":1,"total_count":251},"success":true,"errors":[],"messages":[]}
console.log(myObject["result_info"]["total_pages"])
实际使用:
此脚本在节点中运行,配置模块包含API密钥和资料(由于显而易见的原因,它们不应公开)。
// Import required modules
var request = require('request');
var config = require('./config');
// Setup account details and site details (to edit these variables edit config.js)
var accountemail = config.accountemail;
var globalapikey = config.globalapikey;
// Setup other needed variables
var userfirewallruleids = []; // Store the IDs of each firewall rule in this array
var currentpage = 1;
var pagecount = 0;
// Get the page count (doing the first request twice is less efficient - refactor this in the future)
// Configure Headers (pretend to be CURL for now)
var headers = {
'User-Agent': 'curl/7.47.0',
'Content-Type': 'application/json',
'X-Auth-Email': accountemail,
'X-Auth-Key': globalapikey,
}
// Configure Request
var options = {
url: 'https://api.cloudflare.com/client/v4/user/firewall/access_rules/rules?mode=challenge&configuration_target=country&page=1&per_page=1&order=mode&direction=desc&match=all',
method: 'GET',
headers: headers
}
// Do The Request (in production you can remove the console.log lines or comment it out - by default it'll return the entire response good or bad so you can see what went well or wrong)
request(options, function(error, response, body) {
if (!error && response.statusCode == 200) {
console.log(body["result_info"]["total_pages"]);
} else {
console.log(body);
}
})
然而,与运行console.log(body["result_info"]["total_pages"]);
的概念代码不同,将返回错误。
/Documents/Coding/cloudflare-scripts/remove-user-level-firewall-rules.js:44
console.log(body["result_info"]["total_pages"]);
^
TypeError: Cannot read property 'total_pages' of undefined
at Request._callback (/Users/nathanielsuchy/Documents/Coding/cloudflare-scripts/remove-user-level-firewall-rules.js:44:36)
at Request.self.callback (/Users/nathanielsuchy/node_modules/request/request.js:188:22)
at emitTwo (events.js:125:13)
at Request.emit (events.js:213:7)
at Request.<anonymous> (/Users/nathanielsuchy/node_modules/request/request.js:1171:10)
at emitOne (events.js:115:13)
at Request.emit (events.js:210:7)
at IncomingMessage.<anonymous> (/Users/nathanielsuchy/node_modules/request/request.js:1091:12)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:110:20)
我应该如何修复此脚本,以便直接从API的对象输出中访问页数?
答案 0 :(得分:0)
在深入探讨这个问题后,感谢其他答案和评论,我找到了解决方案。
虽然JSON解析的示例代码有点偏差并且仍然导致错误,但在对JSON解析进行了一些研究之后,我找到了一个解决方案,编写以下代码给了我所需的信息。
console.log(JSON.parse(body)["result_info"]["total_pages"]);
主要的是属性括号表示法需要在JSON解析函数之外。
感谢所有在此提供帮助并帮助我提出此解决方案的人。
答案 1 :(得分:-1)
在访问JSON对象之前需要对其进行解析。
myObject = JSON.parse(body);
console.log(myObject["child"]["nested child"]);