1

My JSON file looks like this:

{
  "branding": {
    "body": {
      "header_text_color": "#224466",
      "body_text_color": "##224466",
      "background_color": "#224466"
    },
    ...
  }
}

In my script I'm trying to import that file, and then to convert it into a JS object:

import templateConfigJSON from '@/config.json'
const templateConfig = JSON.parse(templateConfigJSON)

But I'm getting this error:

Unexpected token u in JSON

What am I doing wrong?

drake035
  • 3,955
  • 41
  • 119
  • 229

2 Answers2

2

JSON.parse() is used to convert a string containing JSON notation into a Javascript object. Since it's already a .json file, you don't need to parse it:

import templateConfigJSON from "@/config.json";
console.log(templateConfigJSON); //outputs object
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • I am not fully d'accord with the explanation "Since it's already a .json file, you don't need to parse it". Usually JSON files or strings require parsing to a JS-object. Here the `import` took care of parsing already. That's why I posted my answer to provide additional explanation – hc_dev Mar 07 '21 at 14:08
0

Might be a misconception of JavaScript import statement. It's used to import files in JavaScript syntax.

The prefixed @ in path is most likely Webpack's resolve.alias which is a stand-in for your source folder. As such the @ alias is configured by Vue for example.

JSON import using a module loader

So when importing a JSON file like this using Webpack (as configured by Vue):

import myObject from "@/myObject.json";

You can immediately and directly use it, like any other JavaScript object previously defined:

const keys = Object.keys( myObject );
console.log( keys );

No parsing required, because this has already be done by import.

See also: How to import a JSON file in ECMAScript 6?

Loading JSON in vanilla JS

In plain vanilla JavaScript you have to load the JSON via XMLHttpRequest and parse it or jQuery offers convenient function:

$.getJSON("test.json", function(json) {
    console.log(json);
    var myObject = JSON.parse(json);
});

See also: Loading local JSON file

hc_dev
  • 8,389
  • 1
  • 26
  • 38