1

I know this will be a very stupid question, but I've been pulling my hair out trying to figure this out. I'm getting the following response back from an API I'm using:

{
  "item_id": "51c3d78797c3e6d8d3b546cf",
  "item_name": "Cola, Cherry",
  "brand_id": "51db3801176fe9790a89ae0b",
  "brand_name": "Coke",
  "item_description": "Cherry",
  "updated_at": "2013-07-09T00:00:46.000Z",
  "nf_ingredient_statement": "Carbonated Water, High Fructose Corn Syrup and/or Sucrose, Caramel Color, Phosphoric Acid, Natural Flavors, Caffeine.",
  "nf_calories": 100,
  "nf_calories_from_fat": 0,
  "nf_total_fat": 0,
  "nf_saturated_fat": null,
  "nf_cholesterol": null,
  "nf_sodium": 25,
  "nf_total_carbohydrate": 28,
  "nf_dietary_fiber": null,
  "nf_sugars": 28,
  "nf_protein": 0,
  "nf_vitamin_a_dv": 0,
  "nf_vitamin_c_dv": 0,
  "nf_calcium_dv": 0,
  "nf_iron_dv": 0,
  "nf_servings_per_container": 6,
  "nf_serving_size_qty": 8,
  "nf_serving_size_unit": "fl oz",
}

And this is the code that I'm trying to run:

var rp = require('request-promise');

module.exports = {
 getIngredients: function(req, callback) {
 rp({
  method: 'GET',
  uri: `https://api.nutritionix.com/v1_1/item?upc=${req.body.upc}&appId=${process.env.NUTRITIONIX_APP_ID}&appKey=${process.env.NUTRITIONIX_APPP_KEY}`
 }).then((data) => {

  console.log(`Talked to NutritionixAPI, result was: ${data}`);
  var ingredients = data.nf_ingredient_statement.split(',');

  console.log(`Ingredients split from the data are: ${ingredients}`);

  return callback(ingredients);

  }).catch((err) => {
   console.log(`Error occured in NutritionixAPI, ${err}`)
   return callback(Object.assign({}, err, { error: true }));
  });
 }
}

What I'm trying to figure out is why data gets printed to the console properly, but as soon as I try to access any value inside, I get the error of it being undefined. I've tried other values in the JSON as well, so I would very much appreciate the help!

EDIT: I want to clarify what the question is about, it's not about the callback and async calls because those work perfectly. My issue is specifically with var ingredients = data.nf_ingredient_statement.split(','); where nf_ingredient_statement is undefined even though obviously it isn't.

ScaVenGerS
  • 61
  • 1
  • 10
  • 1
    Don't take a `callback`. `return` the promise! – Bergi May 03 '17 at 12:51
  • @Bergi: callbacks "work" just fine. Maybe not preferred, but that doesn't seem to be the issue here. The problem here is probably the `return` statement in `return callback(...)` – Cerbrus May 03 '17 at 12:52
  • @Cerbrus The return statement works fine, because everything in the callback runs properly. The issue here is with `var ingredients = data.nf_ingredient_statement.split(',');` where `nf_ingredient_statement` is undefined. – ScaVenGerS May 03 '17 at 12:54
  • 2
    @ScaVenGerS: is `data` a JSON string? (In that case: `data = JSON.parse(data)`) – Cerbrus May 03 '17 at 12:55
  • What exactly would you mean by JSON string, the JSON above is exactly what gets printed to the console (with quotes around key and values). Let me try to parse it as JSON. – ScaVenGerS May 03 '17 at 12:57
  • @Cerbrus Yup, it was a JSON string apparently, I knew the answer would be stupid simple. Thank you! – ScaVenGerS May 03 '17 at 12:59
  • 1
    Then I'd close it as duplicate of: [Parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – Cerbrus May 03 '17 at 13:03

2 Answers2

1

Apparently what I was getting back was a JSON string. So I just needed to do data = JSON.parse(data) to parse it into actual JSON.

ScaVenGerS
  • 61
  • 1
  • 10
0

The problem is that data is a JSON string so you can't access it before parsing it, that's why data.nf_ingredient_statement is undefined.

You need to parse data first, your code should be like this:

var json = JSON.parse(data);
var ingredients = json.nf_ingredient_statement.split(',');
cнŝdk
  • 31,391
  • 7
  • 56
  • 78