JamesG
JamesG

Reputation: 1601

AWS Lambda Parse JSON (Unexpected token)

I am trying to get a Lambda function to access an API and return the JSON.

API

http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a

P.S This API ID is the demo one provided by OW.

Lambda Code

 var jsonurl = "http://api.openweathermap.org/data/2.5/weather?id=2172797&appid=b1b15e88fa797225412429c1c50c122a";
 var data = JSON.parse(jsonurl);
 exports.handler = function(event, context) {
  console.log(data);
  context.done(null, data);  // SUCCESS with message
};

Error

{
  "errorMessage": "Unexpected token h",
  "errorType": "SyntaxError",
  "stackTrace": [
    "Object.parse (native)",
    "Object.<anonymous> (/var/task/index.js:3:17)",
    "Module._compile (module.js:456:26)",
    "Object.Module._extensions..js (module.js:474:10)",
    "Module.load (module.js:356:32)",
    "Function.Module._load (module.js:312:12)",
    "Module.require (module.js:364:17)",
    "require (module.js:380:17)"
  ]
}

Log output

START RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45 Version: $LATEST
Syntax error in module 'index': SyntaxError
    at Object.parse (native)
    at Object.<anonymous> (/var/task/index.js:3:17)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
END RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45
REPORT RequestId: 8ca0fbd1-eee5-11e5-b9dd-31048a8d5a45  Duration: 173.76 ms Billed Duration: 200 ms     Memory Size: 128 MB Max Memory Used: 9 MB

Can anyone see the problem?

What I would like is for lambda to get the json and return it, so anyone looking at my API url will see the results from the Open Weather API

Upvotes: 2

Views: 15807

Answers (1)

Mark B
Mark B

Reputation: 200501

You are passing a URL to JSON.parse(), not a JSON string. First you need to go get the JSON data from the URL using something like http.get(). Perhaps check out the answers to this similar question: Parsing JSON data from a URL

Upvotes: 3

Related Questions