0

I am a self-taught initiate in JavaScript and JSON. I've hit what seems to be an elementary error but can't discern the answer.

I am attempting to read in a file which is formatted JSON text, then parse the file into a JavaScript object. At which point, I get the error:

Uncaught SyntaxError: Unexpected end of JSON input
    at JSON.parse (<anonymous>)
    at objectifyJSONStr (pen.js:54:26)
    at FileReader.fr.onload (pen.js:48:5)

This is the error I get when I run the pen on CodePen. See infra.

I've researched the terms "unexpected end of JSON input" on this forum and have read most of the questions found. Of the ones that seem most to relate to my situation, the answers have been that the JSON was not correctly formatted.

But I have validated the JSON using an online validator (JSONLint - The JSON Validator). (The JSON was formatted in BBEdit for Mac (11.6.4) and saved as a Unicode (UTF-8) file.)

So, that would seem not to be the issue and I am at a loss to see what is wrong.

There is one question on this forum, cors unexpected end of JSON input, that might be relevant but I have the knowledge neither to understand CORS and see how it would be involved here nor to figure out the cure if indeed this is the problem.

The HTML is:

<html lan="en">
  <head>
      <title="A JSON exercise"></title>
  </head>
  <body>

  <input id="FileInput" name="files[]" type="file" accept="application/json" />
  <output id="OutputArea"</output>

  </body>
</html>

The JavaScript is:

document.getElementById('FileInput').addEventListener('change', readFile, false);

var f = {}, fr = {}, file = "", obj = {}, FHCClassSchedule = {};
function readFile(){
    f = document.getElementById('FileInput').files[0];
    fr = new FileReader();
    fr.onload = function(e){
        var el = document.getElementById('OutputArea');
        el.innerHTML += "files[0] : " + f +"<br><br>" + "file : " + fr.result;
        objectifyJSONStr();
    };
    fr.readAsText(f);
    file = fr.result;   
}
function objectifyJSONStr(){
    FHCClassSchedule = JSON.parse(file);
    var el = document.getElementById('OutputArea');
    el.innerHTML += "FHCClassSchedule[0].time : " + FHCClassSchedule[0].time + "<br>" +
                    "FHCClassSchedule[0].instructorImgHref : " + 
                    FHCClassSchedule[0].instructorImgHref + "<br>";
}

The JSON is:

{
   "FHC-Class-Schedule": [
      {
         "time": "0830",
         "room": "A-I",
         "classTitle": "Keynote Address",
         "classDescription": "Room I[content to come]",
         "instructorName": "Crista Cowen",
         "instructorGender": "female",
         "instructorBio": "Crista Cowan has been employed by Ancestry.com since 2004; her involvement in family history, however, reaches all the way back to childhood. From being parked under a microfilm reader at the Family History Library in her baby carrier to her current career as a professional genealogist, Crista has spent thousands of hours discovering, documenting and telling family stories. She is known as The Barefoot Genealogist. You can watch her weekly internet show on the Ancestry YouTube channel.",
         "instructorImgHref": ""
      },
      {
         "time": "0900",
         "room": "A",
         "classTitle": "How To Use Ancestry.com",
         "classDescription": "This presentation is designed for someone new to Ancestry.com and will introduce participants to basic search features in Ancestry.  We will cover how to do a basic search from your family tree, how to use a general search form, and how to perform collection-specific searches.  We will also cover ways to keep learning about how to use Ancestry.",
         "instructorName": "Mindy McLane",
         "instructorGender": "female",
         "instructorBio": "Mindy McLane grew up in northern Minnesota. She majored in Latin American Studies and minored in business management at BYU. She&#39;s been married for 14 years, and working diligently on family history for just about as long. She and her family moved from Iowa to Oklahoma in 2015 when her husband took a job at NSU.",
         "instructorImgHref": "https://static1.squarespace.com/static/546d0ba7e4b03f89760fd462/t/54b4806ae4b043943fa5a471/1463443824178/McLane_Mindy.jpg?format=300w"
      }
   ]
}

There is a reduced case at CodePen, A JSON Exercise. You will need a local JSON file to run it.

EDIT 01:

  • Modified JS per commenters' directions;
  • quoted new error message (line references changed due to changed JS).
Community
  • 1
  • 1
alxfyv
  • 389
  • 1
  • 6
  • 18
  • 1
    if your JSON is already a JSON and you try to `parse` it, I believe that comes up with the error. Can you access it without using `parse`? – A. L Mar 02 '17 at 22:49
  • 2
    `fr.readAsText()` is asynchronous, you need to process the result in the `onload` method. – Barmar Mar 02 '17 at 22:51
  • Put the call to `objectifyJSON()` in the `fr.onload` function. – Barmar Mar 02 '17 at 22:52
  • 1
    `fr.result` only has the JSON content inside of `fr.onload`. before the onload event fires, it is empty. – tklg Mar 02 '17 at 22:52
  • @Barmar: Thank you for your comments. You identified the solution precisely. Thank you for your direction to the earlier question. Although I'm not certain this question is an "exact" duplicate of that one, I understand why you sent me there and am grateful for the opportunity to read it. I did not find it in my earlier searching. – alxfyv Mar 03 '17 at 18:02
  • @Villa7_: Thanks for the explanation. It's so obvious once it's been pointed out. – alxfyv Mar 03 '17 at 18:04
  • @alxfyv Few questions are "exact duplicates", they're just variations on the same theme. The general idea of returning data from asynchronous operations is the same across the board. – Barmar Mar 03 '17 at 20:11

0 Answers0