0

For the project that I am working on, I am using the Shopify API which allows you to retrieve products and other information from your store to be retrieved in the format of a JSON object. I was able to successfully get the JSON object from the API, however when I try to access a property of the JSON object, it returns undefined. I have looked at a couple of articles that I will refrence below, but the problem for those users were things such as needing to use:

JSON.parse()

for a JSON object enclosed by strings which is not my probelem, I have tried a few other work arounds as well but with no luck, I originally thought that the problem was that my code needed to use an "Async/Await" function in order to wait for a response from the API, but I then realized that wouldn't make sense considering I can recieve the whole JSON object itself with no problems.

When I use:

request.get(url, {headers})
.then( result => {
console.log(result); // Only accessing object itself
});

I recieve the JSON object response correctly with no error like this:

     {"products":[{"title":"Test Product 1","body_html":"This is a product that is being tested for retrieval!",
"product_type":"","created_at":"2018-08-21T17:49:07-07:00","handle":"test-product-1","updated_at":"2018-08-21T17:49:07-07:00","published_at":"2018-08-21T17:48:19-07:00","template_suffix":null,"tags":"",
"published_scope":"web","variants":[{"title":"Default Title","price":"5.00","sku":"","position":1,"inventory_policy":"deny",
"compare_at_price":null,"fulfillment_service":"manual","inventory_management":null,"option1":"Default Title","option2":null,"option3":null,
"created_at":"2018-08-21T17:49:07-07:00","updated_at":"2018-08-21T17:49:07-07:00","taxable":true,"barcode":"",
"grams":99790,"image_id":null,"inventory_quantity":1,"weight":220.0,"weight_unit":"lb","old_inventory_quantity":1,
"requires_shipping":true,}],"options":[{"name":"Title","position":1,"values":["Default Title"]}],"images":[],"image":null}]}

However when I use this, the JSON object property returns undefined:

request.get(url, {headers})
    .then( result => {
    console.log(result.products[0]); // Accessing the first item in JSON "products" array
    });

Articles I have already checked out:

cannot access json object property returns undefined

JSON object returns undefined value

JSON objects returns undefined

Would anyone be able to explain my error or why this is happening? I am more than happy to edit my question to include any code/information that might be helpful.

Thanks in advance, Michael

  • Its possible the result is not the json, but a response object that has the json inside it. So maybe you need something like `result.body` or `result.json()`. What do you get when you try to log the whole `result` object? – Jim Perris Aug 22 '18 at 21:40
  • @JimPerris I updated my question to reflect the actual API response I receive. When I log the result itself, that's the exact response that I get – MichaelPopeDeveloper Aug 22 '18 at 21:44
  • you could try adding Items as in Items.products[0] – David White Aug 22 '18 at 21:58
  • @DavidWhite What exactly do you mean? Is that the same as my attempt that goes: result.products[0]? – MichaelPopeDeveloper Aug 22 '18 at 22:03
  • yes. I am not sure what result is doing next to products, maybe result = Items.products[0] or result=products[0]. – David White Aug 22 '18 at 22:06
  • @DavidWhite Just out of curiosity, in your suggestion result = Items.products[0]. Where does the word Items come from? None of my json properties are named items – MichaelPopeDeveloper Aug 22 '18 at 22:08
  • I see Items in most of the JSON I work on. It may not be relevent to your use case. – David White Aug 22 '18 at 22:11
  • if the JSON is not properly formed then JSON methods may not work. Stringify on a bigger dataset like this cumbersome... each dataset is separated by "variable"[ and ends with a ]. regular expressions could well make light work of this once stringyfied... – David White Aug 22 '18 at 22:15
  • Paste the JSON into jsonlint.com, you'll see that it reports an error. There's an extra comma after `"requires_shipping": true`. This is allowed in JavaScript, but not in JSON. – Barmar Aug 22 '18 at 22:29
  • @DavidWhite It ended up[ being related to what you said, I needed to stringy the data in order to access it, thank you! I gave you the answer. – MichaelPopeDeveloper Aug 23 '18 at 17:12

3 Answers3

0

try this:

console.log("data:", JSON.stringify(result.products[0], null, 2));

console.log to print the result to your console. Use Chrome and developer tools and you will see a console option - excellent for debugging.

JSON.stringify turns the JSON data into something you can see and read. You can convert the data and then split as you need this way too.

OK, a second answer. I can't check this, as I don't have your JSON data, however, I would try something that would likely resemble this...

data.Items[0].field

if the data is not correctly formatted then take the stringify approach and split it out. Otherwise, consider this:

products":[{"title":"Test Product 1"

variable = products[0].title;

I would tend to use a function to pull all the data out in one shot.

function Getv(data){    global.myApp.v = JSON.stringify(data, null, 2); }

then I might run this...

 Getv(data.Items[0]); let splitData = global.myApp.v.split('\"'); let vCount= splitData.length; 
David White
  • 621
  • 1
  • 10
  • 23
  • sometimes the stringify is just a crude and fast way to get at the data, there are other ways. I will give you another answer – David White Aug 22 '18 at 21:44
  • Sorry about changing them, I replaced them with the answer you gave me and I receive the following error: TypeError: Cannot read property '0' of undefined – MichaelPopeDeveloper Aug 22 '18 at 21:51
  • Thank you for this response! I am able to retrieve the data, however its stored into an array in about 100 different sections, its retrieves it, just chops it up a lot more than intended! I'm currently trying to find a way to fix that – MichaelPopeDeveloper Aug 22 '18 at 22:05
0

if the object returns like this it wouldn't work because it's missing a colon after "products" identifier. like Luca said it's not a valid JSON response

Umit
  • 47
  • 1
  • 7
0

Try this:

var resultJson = JSON.parse(result);

console.log(resultJson.products[0].varname);
John
  • 36
  • 3