How do I access this property of an object from a RESTful API?

Home / javascript / How do I access this property of an object from a RESTful API?

Question:
I’m writing to the community today as I’m having some confusion while trying to access an Object Provided by an API.

API Used:Cloudflare’s v4 API is used: The applicable documentation is available at https://api.cloudflare.com/#user-level-firewall-access-rule-list-access-rules

Concept:
I’ll receive an object identical to myObject when accessing the API however to make sure that we understand the object I’ve included source code that can access it below.

The object with pretty formating
{
"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": []
}
The code below returns the number 251 without issue which is what’s expected.
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"])
In real use:
This script is ran in node, the configure module contains API Keys and Stuff (they shouldn’t be exposed for hopefully obvious reasons).
// 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);
}
})
However unlike the concept code running console.log(body["result_info"]["total_pages"]); will return an error.
/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. (/Users/nathanielsuchy/node_modules/request/request.js:1171:10)
at emitOne (events.js:115:13)
at Request.emit (events.js:210:7)
at IncomingMessage. (/Users/nathanielsuchy/node_modules/request/request.js:1091:12)
at Object.onceWrapper (events.js:314:30)
at emitNone (events.js:110:20)
How should I go about fixing this script so I can access the page count directly from the API’s Object Output?


Answer:
JSON objects need to be parsed before being accessed.

myObject = JSON.parse(body); console.log(myObject["child"]["nested child"]);
Read more

Leave a Reply

Your email address will not be published. Required fields are marked *