0

I have extracted JSON content from this web site

Have created some code in Google Script Editor...

var urlresponse = UrlFetchApp.fetch(url).getContentText().substring(3);
var jsondata = JSON.stringify(urlresponse);
var jsonparseddata = JSON.parse(jsondata);

I can print the jsonparseddata to the logs as below. But cannot seem to get a value or even attempt to iterate. Have spent hours trying various online examples, need help. Thanks

When using jsonparseddata[0].id the logs return 'undefined'

[{
    "id": "22144",
    "t": "AAPL",
    "e": "NASDAQ",
    "l": "90.52",
    "l_fix": "90.52",
    "l_cur": "90.52",
    "s": "0",
    "ltt": "4:00PM EDT",
    "lt": "May 13, 4:00PM EDT",
    "lt_dts": "2016-05-13T16:00:02Z",
    "c": "+0.18",
    "c_fix": "0.18",
    "cp": "0.20",
    "cp_fix": "0.20",
    "ccol": "chg",
    "pcls_fix": "90.34"
}]
Tommy
  • 1
  • 1
  • 6
    Take a look at [Parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/parse-json-in-javascript) – blacktide May 14 '16 at 22:47
  • You have a JSON array. Do `jsonparseddata[0].id` to read the id, `jsonparseddata[0].e` to see "NASDAQ" etc – Moses Koledoye May 14 '16 at 22:54
  • I've 'parsed' the JSON. But I need to extract values – Tommy May 14 '16 at 22:55
  • jsonparseddata[0].id returns 'undefined' in the log. – Tommy May 14 '16 at 22:56
  • Try `jsonparseddata[0]['id']` instead – Moses Koledoye May 14 '16 at 23:14
  • OK - think I'm getting somewhere. jsonparseddata is a string not an object. The problem right at the start is the JSON web site content begins with // so I have used substring to get rid of this. But now probably need to get back into a JSON Object which I thought Parse would do – Tommy May 14 '16 at 23:17
  • Cracked it - var jsondata = JSON.stringify(eval(urlresponse)); now jsonparseddata returns as an object. The rest of the code now responds correctly to jsonparseddata[0].id. Will leave iteration for tomorrow. – Tommy May 14 '16 at 23:26

1 Answers1

0

Added logging to show the type of each variable.

As I used .getContentText().substring(3); for the urlresponse due to badly formatted JSON on the web site, this made each subsequent variable a string.

Using EVAL - var jsondata = JSON.stringify(eval(urlresponse)); Now the jsonparseddata is an object and jsonparseddata[0].id is returning a value, instead of undefined.

Tommy
  • 1
  • 1