Having trouble transforming my JSON file into a JavaScript object

I have a JSON file with the following structure:

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

When attempting to import this file in my script and convert it to a JavaScript object, I use the following code snippet:

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

However, I encounter the following error message:

Unexpected token u in JSON

What could be causing this issue?

Answer №1

JSON.parse() function is commonly used in JavaScript to convert a string that contains JSON notation into a JavaScript object. However, if the data is already in a .json file, there is no need to use parse method:

import templateConfigJSON from "@/config.json";
console.log(templateConfigJSON); //outputs object

Answer №2

One common misunderstanding is related to the JavaScript import statement, which is utilized for importing files in JavaScript syntax.

The presence of the prefix @ in a path is likely associated with Webpack's resolve.alias, serving as a substitute for the source folder. This alias can be configured by frameworks like Vue, as explained in this Stack Overflow post.

Importing JSON using a module loader

In scenarios where you need to import a JSON file using Webpack (configured by Vue), you can do so like this:

import myObject from "@/myObject.json";

Once imported, you can directly utilize the content without requiring any additional parsing, treating it as a regular JavaScript object:

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

Since the parsing is done during the import process, there's no need for separate parsing steps.

For further insights, refer to: How to import a JSON file in ECMAScript 6?

Loading JSON in native JS

In pure vanilla JavaScript, loading JSON involves utilizing methods like XMLHttpRequest for fetching and parsing data. Alternatively, jQuery provides a convenient function for this purpose:

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

Explore more about this topic here: Loading local JSON file

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When using iOS, the video compressing process stops automatically if the screen is no longer active while the file input

I am working on a web application that includes a file upload feature for large videos, typically 30 minutes or longer in duration. When a user on an iOS device selects a video to upload, the operating system will automatically compress it before triggerin ...

Tips on sending access token and store name to a new object in Shopify API Node

In the process of developing a public Shopify app, I am looking to implement a POST route for creating a metafield. According to the documentation found in the shopify-api-node module, it states: accessToken - Necessary for public apps - This is a string ...

Exploring the intricacies of JSON information

Greetings, coding comrades! I have come across a URL and I am tasked with fetching JSON data hosted on it. As a newbie to JSON, I must admit that while I can decipher some of the data, there are certain "strange" characters within the JSON data that piqu ...

What is the best way to retrieve an element from an array within a script?

As a newbie in the realm of vue and Laravel Framework, I am eager to fetch data from an API and display it dynamically on my web page. To achieve this, I have already set up a table named 'Progress' where I seeded some initial data. Utilizing AP ...

Configuring Laravel and Vue together

Good evening, I am encountering an issue while trying to install Vue into my project. The error occurs when I run the command npm run watch. Can anyone provide assistance on how to troubleshoot and resolve this problem? 0 info it worked if it ends with o ...

Retrieving values from nested arrays in Vue.js

I'm currently delving into Vue3. My goal is to extract the values from an array within an array in order to create a neat table. Once extracted, I plan to separate these values with commas. For more information, you can visit this link: https://stack ...

use ajax to selectively update specific element

Seeking assistance with updating the cart page using ajax when adjusting the quantity of products. The view logic seems to be functioning correctly. The issue arises when targeting the class "ajax_updater". Upon clicking the quantity buttons, ajax succes ...

Avoid Scrolling within an iFrame in HTML with the Use of #

I have a menu loading in an iframe with links using # like http://<location>/page.html#part1. When I click inside the iframe, the entire page outside of the iframe scrolls to the location of #. How can I stop this from happening? I only want the me ...

How can I load a .json file into JavaScript without inserting it directly into the code?

Currently, I am dealing with a lengthy JSON snippet that resembles the following: { "section: [ [stuff] ] } To incorporate this into my JavaScript code, I currently use the following approach: var obj = { // {All the stuff from above} } My ...

Can the table be automatically updated on page reload?

My goal is to populate a table using $.ajax(), but the content is not showing up when the page first loads. Is there something missing in my implementation of the $.ajax() function? Here's the HTML structure: <div class="row"> <div clas ...

How can I display a Skeleton when pressing pagination buttons and then turn it off after 3 seconds?

Here is a snippet of my code featuring the use of a Skeleton as a placeholder for CardMedia: {loading ? ( <Skeleton variant="rectangular" width={308} height={420} animation="wave" /> ) : ( <CardMedia s ...

Adjust the content of a table cell using jQuery

<td>09 Mars 2020</td> Using the string above, I have created a div. Here are the Jquery variables I am working with: date1 = 09 Mars 2020 date2 = 18 Mars 2020 My goal is to combine the content from another date with the existing date to ach ...

jquery accordion failing to display content

Upon navigating to my website and accessing the webpage featuring an accordion, the accordion successfully appears and hides after 1500ms as intended. However, when attempting to reveal the text by clicking on the headings, nothing happens. The heading sim ...

What is the process for adding routes prior to implementing jsonwebtoken?

I am currently working with jsonwebtoken and I have some questions about how it functions. I have regular sign-in and sign-up routes that should come before the .verify function. Although I have experience using jwt in the past, this is my first time imple ...

unable to add browse-sync to Ubuntu 16.04

I recently installed nodejs and npm and attempted to install browser-sync using the command npm install -g browser-sync. However, I encountered an error. npm install -g browser-sync npm ERR! Linux 4.15.0-101-generic npm ERR! argv "/usr/bin/nodejs" "/ ...

Adjust the color of the text as it scrolls by

As I work on developing my website using the Neve Theme on WordPress, I have encountered an issue with customizing the header block. I am using a plugin to set a background color for the header after scrolling 100px down the page, but this makes the text h ...

Using PhoneGap to load JSON data with the File API when clicking an event

I have successfully developed code that loads JSON data from an external file on the device. The program is designed to work as follows: Upon a click event, it will first attempt to access the local storage file (course.txt) and if it exists, it will read ...

Observing the HTMLInputElement Object in Action with JavaScript

After utilizing JavaScript to extract the value from the SPAN element, placing it into a hidden form field, and submitting the data, I am puzzled by the unexpected result I am receiving. Can you help me understand why this is happening? <form onsubmit= ...

The complexities of stopPropagation() causing further confusion

I have encountered an issue with my code. It currently allows a dropdown functionality for a <ul> element, but when a child <li> is clicked, it also closes other menus of the same type. To fix this, I used an if clause to check if the clicked ...

The HTML body content of an iframe

Hey there, I'm trying to get just the body html from an iframe using my code. Currently it returns all the html of the iframe. Does anyone have any ideas on how to modify this? Here's the code snippet: alert( $("#uploaderIframe").contents()[0]. ...