0

i am still relatively new to the whole JavaScript environment and i need help with parsing a JSON file into a JSON object to read the contents of the file. I have been reading a lot of other questions and documentation but so far i have not seen anything relevant to my question.

First the situation: I have a file called test.json which is supposed to be delivered from a server. But for testing purposes it is stored locally as clusters.json, in the same folder as my html document. Code for HTML file:

<!DOCTYPE html>
<meta charset="utf-8">
<html>
<head>
    <title>JSON THINGIE</title>
</head>
<body>
    <h1>A Header</h1>
    <p id="textone">sample text</p>
    <script>
        var jsonFile = "/clusters.json";
        var jsonObj = JSON.parse(jsonFile);
    </script>
</body>
</html>

The codes executes untill JSON.parse(jsonTest);, then it throws this error (from mozilla debug tool):

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

JSON File (clusters.json)

{
    "occupation":{
      "employment":[
         {
            "id":1,
            "cluster_name":"Tekenaar",
            "weight":0.5,
            "similarity":0.1,
         },
         {
            "id":4,
            "cluster_name":"Tekenaar Constructeur",
            "weight":0.6,
         }
      ],
      "education":[
         {
            "id":2,
            "cluster_name":"HBO",
            "weight":1,
         },
         {
            "id":3,
            "cluster_name":"HBO",
            "weight":1,
         }
      ]
   }
}

Appearantly the { opening bracket is wrong but the JSON docs state that files can be opened with { or [.

I have checked my JSON with multiple validator tools and even used a copypaste from the JSON Example page but everything gives the same error.

Also in accordance to the answer to this question, i tried using JSON.stringify(jsonTest) first, but to no avail.

What could i possibly be doing wrong? Any help is appreciated since i am already spending too much time on this error. Thanks.

Edit 1: It was indeed my own mistake of thinking that using a string would make the parser load the file automatically.

Serverless Fix: I succeeded in loading the text from the file by using the answer to this question. Which i arrived at when i was searching for how to use file://.

Implementation of fix for future reference:

// URL to the file
var jsonFile = 'file:///C://Users//Daan//Projects//Temp Name//clusters.json'

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                var allText = rawFile.responseText;
                // Show alert with the read text.
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

readTextFile(jsonFile);

3 Answers 3

1

The line var jsonFile = "/clusters.json"; doesn't load the file, it just creates a string. The next line is trying to parse the string as a JSON object, which it is not. You will have to load the file somehow before trying to parse its content.

You will probably need a webserver to run your website on, if you don't have that already, and load the file using AJAX.

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

4 Comments

Is it possible to load a file without using the XMLHttpRequest() function?
Yeah, I believe it is. You should do something like this: jsonFile = 'file://c:/my/dir/structure/clusters.json'. And it only works as long as the HTML file is served from disk and the json file is on disk.
Or perhaps you can use the FileReader, see here for more info: html5rocks.com/en/tutorials/file/dndfiles. But I think that only works when the load is triggered by a user interaction like clicking on a button. I think an AJAX call will be your best bet.
Thank you @Thijs, i fixed it. I shall update the post shortly to show my fix.
0

Try without the JSON.parse(xxx)

You can remove var jsonObj = JSON.parse(jsonFile);

JSON.parse is trying to convert your file in a JSON format which is JSON already.

Just use jsonFile in your code.

Comments

0

From your code it looks like you are trying to give JSON.parse() a file name as a parameter. JSON.parse() accepts a string. You'll have to get your hands on the file contents and then pass this to JSON.parse(). This answer may be helpful.

JSON.parse() documentation

Comments

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.