skip to Main Content

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


  1. Chosen as BEST ANSWER

    Got it to work finally

    var response = req.response;
    var jsonData = JSON.parse(response.body)
    
        var articleList_json = [];
        var i;
        
        for (i = 0; (i < 15 && i < jsonData.data.all_insight_article.items.length); i++) {
          articleList_json.push({
            "title": jsonData.data.all_insight_article.items[i].title.toString()
          });
        }
        logInfo("Count "+i);
        
        logInfo(JSON.stringify(articleList_json));
    

    console log of array of objects

    [
      {
        "title": "Six key differences between private equity and public market investing"
      },
      {
        "title": "Securing the supply of rare earth metals is central to our energy transition"
      },
      {
        "title": "Test article for charts"
      },
      {
        "title": "Central banks hike rates again - but for how much longer?"
      }
    ]
    

  2. JSON.parse() takes a string in json structure and parses it:

    The JSON.parse() static method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    JSON string example:

    const json = '{"result":true, "count":42}';
    const obj = JSON.parse(json);
    

    HttpClientRequest returns a HttpClientResponse object which you must first convert to a string before parsing it (on the condition that the returned string is in valid json structure):

    var content = response.body.toString(response.codePage);
    var posts = JSON.parse(content);
    

    https://experienceleague.adobe.com/developer/campaign-api/api/p-HttpClientResponse-body.html

    Full documentation example:

    var http = new HttpClientRequest("http://www.google.com/")
    http.execute()
    var response = http.response
    if( response.code != 200 )
      throw "HTTP request failed with " + response.message
    var content = response.body.toString(response.codePage)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search