2

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

1 Answer 1

3

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

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

2 Comments

When I use http.get() in Lambda I get the error message : "errorMessage": "http is not defined",
Well did you define it? var http = require('http');

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.