2

I'm trying to write a loop for an array but getting an invalid string error.

If keyword = "mesothelioma|seo"

function json(keyword) {
  var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carterq="+keyword);
  var object = Utilities.jsonParse(jsondata.getContentText());

  var results = Array("Error", "Error", "Error", "Error");

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  return results;
}

Any thoughts?

1 Answer 1

2

Your reference error is coming from this line:

var jsondata = UrlFetchApp.fetch("http://api.grepwords.com/lookup?apikey=carter&q="+keyword);

From your above code, this is the only moment where you use 'keyword'. You sure it returns the correct information? And if it does have you thought about your loop?

Suppose your var object = Utilities.jsonParse(jsondata.getContentText()); returns this:

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];

And we use your loop:

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

You do realize you never use 'i'? and you overwrite what you had in results with the same thing after each loop? Are you sure you wanted this?

function somefunc() {

  var object = [
      {cpc: 'test1', cmp: 'test2', lms: 'test3', m1: 'test4'},
      {cpc: 'test5', cmp: 'test6', lms: 'test7', m1: 'test8'},
      {cpc: 'test9', cmp: 'test10', lms: 'test11', m1: 'test12'}
  ];
  var results = Array("Error", "Error", "Error", "Error");

  if (object[0] != undefined)
  {
  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  for (var i = 0; i < object.length; i++) {

  results[0] = object[0].cpc;
  results[1] = object[0].cmp;
  results[2] = object[0].lms;
  results[3] = object[0].m1;
  }

  return results;
}

console.log(somefunc());

Sign up to request clarification or add additional context in comments.

1 Comment

Which part is giving you the invalid json string? :P Be a little more precise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.