Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Node.js Basics 2017 Create a Command Line Weather Application Parsing Data and Printing - Solution

unexpected token in JSON at position 4

When I try to run my code in the console, I just get the Syntax error message,

module.js:675 throw err; ^

Syntax error: home/treehouse/workspace/api.json: Unexpected token in JSON at position 4

const https = require('https');
const querystring = require('querystring');
const api = require('./api.json');

// Print out temp details
function printWeather(weather) {
  const message = `Current tempature in ${weather.location.city} is ${weather.current_observation.temp_f}F`;
  console.log(message);
}

// Print out error message

function get(query) {
    const parameters = {
      APPID: api.key,
      units: 'imperial'
    };

    const zipCode = parseInt(query);
    if (!isNaN(zipCode)) {
      parameters.zip = zipCode + ',us';
    } else {
      parameters.q = query + ',us';
    }

    const url = `http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={api-key}?${querystring.stringify(parameters)}`;
    console.log(url);

    const request = https.get(url, response => {
        let body = "";
        // Read the data
        response.on('data', chunk => {
            body += chunk;
        });
        response.on('end', () => {
            console.log(body);
            //Parse data
            printWeather(weather);
            //Print the data
        });
    });
}

module.exports.get = get;

//TODO: Handle any errors

1 Answer

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 91,252 Points

It's telling you there's a syntax error somewhere in your JSON file. But these errors don't really tell you what is causing the error and JSON syntax isn't really forgiving when it comes to errors.

I would suggest you find a syntax code checker on the contents of your api.json file and see what it comes up with. :-)