Venator
Venator9mo ago

Importing JSON files with a different file extension fails as "Unknown module"

When trying to import a json file with import attributes that doesn't end with .json Deno gives the following error:
error: Expected a Json module, but identified a Unknown module.
Specifier: file:///C:/path/to/jsonfile.ldtk
error: Expected a Json module, but identified a Unknown module.
Specifier: file:///C:/path/to/jsonfile.ldtk
The code for importing it looks like this:
import jsonfile from './path/to/jsonfile.ldtk' with { type: 'json' };
import jsonfile from './path/to/jsonfile.ldtk' with { type: 'json' };
When renaming the file to .json and updating the import accordingly, it works as expected. Is this a known limitation, something I can work around, or a bug? I couldn't find anything on it.
1 Reply
Deno AI Helper
Deno AI Helper9mo ago
Based on the documentation, Deno determines the type of a file based on its extension for local modules. For JSON files, the extension should be .json. When the extension is absent or different, Deno assumes it to be a JavaScript file. This is likely why you're encountering an error when trying to import a JSON file with a different extension. As a workaround, you could read the file as text using Deno.readTextFile() and then parse it with JSON.parse(). Here's an example:
const text = await Deno.readTextFile("./path/to/jsonfile.ldtk");
const jsonData = JSON.parse(text);
console.log(jsonData);
const text = await Deno.readTextFile("./path/to/jsonfile.ldtk");
const jsonData = JSON.parse(text);
console.log(jsonData);
Please note that this workaround isn't explicitly mentioned in the documentation, but it's a common way to handle JSON data in JavaScript and TypeScript.