I am querying a graphQL endpoint through http request and I am getting a successful response with the data that I need to collect, however, I can’t seem to navigate through the data to pull the fields I require.
const query = JSON.stringify({query:
'{' +
' all_insight_article('+
' locale: "en-gb"'+
' where: {business_unit: {business_unit: {title: "Some Brand"}, MATCH: ALL}, audience: {MATCH: ALL, audiences: {title: "Management"}}publish_date_gt: "2023-02-01"}'+
' ) {items {'+
' audienceConnection {'+
' edges {'+
' node {... on Audiences {title system {uid}}}}}'+
' system {'+
' uid'+
' publish_details {time}'+
' updated_at}'+
' absolute_url'+
' title'+
' subtitle'+
' main_image'+
' topicsConnection {'+
' edges {'+
' node {'+
' ... on Topics {'+
' title'+
' display_name'+
' system {uid}}}}}}total}}'
});
var req = new HttpClientRequest("https://eu-graphql.contentstack.com/stacks/bltcxxx?environment=xxx&access_token=xxx")
req.header["Content-Type"] = "application/json"
req.method = "POST"
req.body = query
req.execute()
var response = req.response;
var posts = JSON.parse(response.body);
var articleList_json = [];
var i
for ( i = 0; i < 15; i++) {
articleList_json.push({
"title": posts[i].title,
});
}
logInfo(articleList_json);
The error I get is posts is undefined.
Note: HttpClientRequest
is a class for my application, but is pretty much a standard http request https://experienceleague.adobe.com/developer/campaign-api/api/c-HttpClientRequest.html
2nd update
I tried the following but still does not work
var response = req.response;
var posts = JSON.stringify(response.body);
var articleList_json = [];
var i
for ( i = 0; i < 15; i++) {
var graphQLJSON = JSON.parse(posts[i]);
articleList_json.push({
"title": graphQLJSON.data.title,
});
}
logInfo(articleList_json);
2
Answers
Got it to work finally
console log of array of objects
JSON.parse()
takes a string in json structure and parses it:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse
JSON string example:
HttpClientRequest
returns aHttpClientResponse
object which you must first convert to a string before parsing it (on the condition that the returned string is in valid json structure):https://experienceleague.adobe.com/developer/campaign-api/api/p-HttpClientResponse-body.html
Full documentation example: