0

Perhaps a simple question but I am still new to JS / nodeJS.

I have a script that is doing some basic string matching (dict.js), and I am trying to access a JSON formatted object from another file (words.json) to iterate through.

The directory structure looks like:

scratch
- algorithms
  - dict.js
- utilities
  - words.json

The contents of the files are:

words.json

{"a": 1,"aa": 1,"aaa": 1,"aah": 1,"aahed": 1,"aahing": 1,"aahs": 1,"aal": 1}

dict.js

decode (password) {
    
    const jsonData = require('../utilities/words.json'); 
    myObj = JSON.parse(jsonData);

    for (const x in myObj) {
        console.log(x)
        // compare password against item in words.json
    }
    console.log(Object.keys(myObj).length)

    return "stub";
}

I am getting an error in developer tools when I create a block (this is the backend to a block in Scratch) that uses this Decode function.

Uncaught SyntaxError: Unexpected token o in JSON at position 1

Thanks

  • 1
    `Unexpected token o` whatever you're trying to parse is likely to be the string `[object Object]` - try `JSON.parse({})` and you'll see the same error - more than likely `jsonData` is an object, not JSON at all so `const myObj = require('../utilities/words.json');` replaces the first two lines of the function – Bravo Mar 11 '22 at 02:17

1 Answers1

0

In nodejs environment you can directly import json file data without parsing it. For exaple:

const myObj = require('../utilities/words');

This gives you the data in your json file as a ready-to-go object.

In your case, you are trying to parse json object with JSON.parse() which expects stringified json. So just remove the part JSON.parse(jsonData);

ABDULLOKH MUKHAMMADJONOV
  • 4,249
  • 3
  • 22
  • 40