Skip to content
Advertisement

Cannot get my GRAPHQL response into an iterable JSON format

so a bit of background. I am making a GRAPHQL call to shopify’s graphQL api. I am getting data back (yay!) and it is correct (double yay!!), unfortunately I cannot then do very much with the data other than look at it – I cannot iterate through it with regular JSON syntax. My plan is to then have the data be put into javascript generated HTML elements to display to the user e.g. generate a list with the titles/pictures of the products.

Without further ado, my code.

Step 1: a JS function to respond to my keypresses and run an async fetch:

JavaScript

Step 2: my async fetch call to the php script

JavaScript

Step 3: my php script itself running the graphQL call, done with curl

JavaScript
JavaScript

3b: the code that preps the query for the graphQL func $query1 uses the $_POST[] to get the $searchString from the front end to the backend

JavaScript

$query1 is passed through the graphQLCall() and then its response, which is the id of the product is then passed into a 2nd query to then call the product itself: 3b of the php script:

JavaScript

It then pushes the response into an array, so I am left with an array full of queries with the correct product id. Next that array is iterated through in order to call the products themselves. 4b of php script:

JavaScript

The final step in my php script is to print_r($json);

after which it is then processed by my async showGraphQL() function; written above.

My async fetch responds with something like this when I post to innerHTML:

JavaScript

The above response is totally correct but, the problem occurs when I try to place it in a html element like: graphQL[i].data.product.id I receive undefined. That is my problem that I am unable to correctly iterate through what appears to be a JSON.

I am new to graphQL and to using API’s in general so appreciate any help and apologize that its so longwinded, I hope the question/problem is clear and that the code is presented clearly too.

  • Boogabooga

Advertisement

Answer

So in case anyone finds this later and runs into the same problem. Going off of what @morganney said, I was receiving an Object. So by my logic, which is not the logic you want to lead you into battle but whatever, I need to parse this object into a JSON using JSON.parse() so. I did NOT change my PHP script but rather my JS async graphQL() This is my edited async GraphQL() func

JavaScript

Confusingly, I loop through my graphQL variable, and call JSON.parse(graphQL[i]) on it, I am then able to console.log specific values of the now JSON.

I hope this helps someone someday and thanks to the people who commented.

  • Boogabooga
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement