JavaScript Node.js Basics Building a Command Line Application Parsing JSON

aleti chaitanya
aleti chaitanya
3,588 Points

Unexpected token i in JSON at position 1:

i cannot parse the json data in the below code. please help me i am getting "Unexpected token i in JSON at position 1" when ever i want to parse the data into json object.

var https = require("https"); var username = "aletichaitanya";

https.get(https://teamtreehouse.com/${username}.json, res => { console.log(res.statusCode); var body; res.on("data", d => { body = d.toString(); }); res.on("end", () => { var parsing = JSON.parse(body); console.log(parsing); }); });

this is the error message that pops up in the terminal:

SyntaxError: Unexpected token i in JSON at position 1 at JSON.parse (<anonymous>) at IncomingMessage.res.on (F:\chaitu\web tech practise\js\js.js:12:24) at emitNone (events.js:111:20) at IncomingMessage.emit (events.js:208:7) at endReadableNT (_stream_readable.js:1064:12) at _combinedTickCallback (internal/process/next_tick.js:138:11) at process._tickCallback (internal/process/next_tick.js:180:9) PS F:\chaitu\web tech practise\js>

1 Answer

Fabio Marcel Ramos da Costa
Fabio Marcel Ramos da Costa
8,241 Points

There are some errors in your code:

  1. You must enclose the URL string in backticks (`) to use Template Literal:
    `https://teamtreehouse.com/${username}.json`
  1. You must assign an empty string to the variable body:
    var body = ''; 
  1. You must concatenate the variable body inside the data callback:
    body += d.toString();

4, As you parsed the variable body from JSON to JavaScript object, you must use the dir method of the console object:

    console.dir(parsing);

So your code should look like this:

var https = require("https"); 
var username = "aletichaitanya";

https.get(`https://teamtreehouse.com/${username}.json`, res => { 

    console.log(res.statusCode); 

    var body = ''; 

    res.on("data", d => { 

        body += d.toString(); 

    }); 

    res.on("end", () => { 

        var parsing = JSON.parse(body); 
        console.dir(parsing); 

    }); 
});