Deepak singh
Deepak singh

Reputation: 35

SyntaxError: Unexpected token e in JSON at position 1 with JSON.parse()

I am trying to use openweathermap.org weather api, I am getting the data but having trouble parsing it.

Here's my code:

request("https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric&callback=test", function(error, response, body) {
    if (!error && response.statusCode == 200) {
        var parsedData = JSON.parse(body);
        console.log(typeof body);
    }
});

console.log(typeof body); returns string so I just can't figure out what 's the problem.

Upvotes: 0

Views: 876

Answers (4)

Ida Silfverskiold
Ida Silfverskiold

Reputation: 21

Remove &callback=test at the end of your URL then you don't have to deal with JSONP and you can work with it like normal.

Upvotes: 1

Samuel
Samuel

Reputation: 6136

This worked for me. Just set object for the first argument with url and json property. set json:true. Setting to true will handle the parsing for you :)

const request = require('request');
const url = "https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric";

request({ url: url, json: true }, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body);
  }
});

As @mplungjan pointed out. That's a JSONP url.

Upvotes: 1

mplungjan
mplungjan

Reputation: 177754

You are looking for this - the URL is JSONP so it expects a function called test and no need to parse

<script>
const test = data => console.log(data);
</script>
<script src="https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric&callback=test"></script>

Alternatively remove the callback - here using fetch:

fetch("https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric")
  .then(response => response.json())
  .then(data => console.log(data));

Or Axios

axios.get('https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric')
  .then(response => console.log(response.data));
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Upvotes: 1

Rush W.
Rush W.

Reputation: 1361

Since you are using an API which has a callback function return as response. It is not JSON but JSONP (JSON with Padding). Your code will work just fine if you remove the callback parameter from URL.

request("https://api.openweathermap.org/data/2.5/weather?lat=30.4831&lon=76.595&appid=7beb6de85d3f3a28dabda1015684562f&units=metric", function(error, response, body) {
       if (!error && response.statusCode == 200) {
          console.log(response);
       }
   });

For further reading about JSONP, You can refer this.

Upvotes: 0

Related Questions