I'm trying to load a JSON file into my ReactJS application, but any of the following methods I've tried the following:
Require:
const countries =require('../../json/countries.json');
// Also fails the exact same way with redundant parse call:
const countries = JSON.parse(require('../../json/countries.json'));
Importing using json-loader
:
import countries from '../../json/countries.json';
Using the following loader in loaders
{
test: /\.json$/,
loader: 'json-loader'
}
The JSON loads, but fails to parse:
./src/app/json/countries.json
Module build failed: SyntaxError: /src/app/json/countries.json:
Unexpected token, expected ; (2:6)
1 | {
> 2 | "BD": "Bangladesh",
| ^
3 | "BE": "Belgium",
4 | "BF": "Burkina Faso",
5 | "BG": "Bulgaria",
The countries.json file is valid JSON downloaded from http://country.io
, but it seems the quotes are causing an issue. But this is valid JSON being loaded by JavaScript, so it should work together seamlessly.
Any idea what the problem is?
SOLVED
I solved this issue by changing the loader
directive into use
:
let config = {
module: {
loaders: [
...
{
test: /\.json$/,
use: {
loader: 'json-loader'
}
}
]
}
};