Parsing error: 'Unexpected token' found in JSON while attempting to access an external file

Currently working on implementing backbone for a new project along with underscore, requirejs, jquery, and bootstrap. Things are progressing smoothly as I aim to include static survey question data into one of the data models.

{
    "defaultOptions": {
        "1": "Strongly Agree", 
        "2": "Somewhat Agree",
        "3": "Have Mixed Feelings",
        "4": "Somewhat Disagree",
        "5": "Strongly Disagree",
        "6": "Have No Opinion",
        "7": "Do Not Wish To Respond"
    },
    "questions": {
        "1": {
            "question": "Question 1",
            "options": {}
        },
        "2": {
            "question": "Question 2",
            "options": {}
        },
        "3": {
            "question": "Question 3",
            "options": {}
        },
        "4": {
            "question": "Question 4",
            "options": {}
        },
        "5": {
            "question": "Question 5",
            "options": {}
        }
    }
}

Currently without access to the final data API intended for the project, using dummy data extracted from the previous version related to the US Elections cycle which occurs annually. Separating out some static content model data into a different file to prevent accidental alterations. Working within the same server constraints and processing JSON through for validation.

Encountering an error in Chrome "Uncaught SyntaxError: Unexpected token : on line 2" and FireFox displays 'SyntaxError: missing ; before statement "defaultOptions":', focusing on the : following defaultOptions.

Calling two json files consecutively:

var survey = require('/elections/data/surveyQuestions.json');
var endorsements = require('/elections/data/endorsements.json');

No issues with endorsements.json file or other required contents. Referencing endorsements.json below:

[
    "Abortion Rights Council",
    "AFL-CIO",
    "AFSCME",
    "American Federation of Teachers",
    "Building and Construction Trades Council",
    "DFL Feminist Caucus",
    "DFL Party",
    "Education Minnesota",
    "Freedom Club",
    "GOP Feminist Caucus",
    "Grassroots Party",
    "Green Party of Minnesota",
    "Independence Party",
    "Libertarian Party of Minnesota",
    "MAPE",
    "Minnesota Citizens Concerned for Life",
    "Minnesota Police and Peace Officers Association",
    "National Association of Social Workers",
    "Republican Party of Minnesota",
    "Sierra Club",
    "Stonewall DFL",
    "TakeAction Minnesota",
    "Taxpayers League of Minnesota",
    "Teamsters DRIVE",
    "United Auto Workers"
]

Any insights on resolving the issue would be greatly appreciated.

Answer №1

When you use the require() function in RequireJS, it expects an AMD module to be called. To load text resources like JSON, it is recommended to utilize the RequireJS text plugin. Additionally, there is a useful plugin available on this GitHub gist for parsing JSON specifically, which is built upon the text plugin.

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

What is the best way to transfer a PHP string to JavaScript/JQuery for use in a function?

Within my PHP code, I have the following: $welcome = "Welcome!"; echo '<script type="text/javascript">addName();</script>'; Additionally, in my HTML/script portion: <a id="franBTN"></a> <script type="text/javascript ...

Unable to use global modules in NestJS without importing them

Currently, I am in the process of integrating a global module into my nest.js project I have written a service as shown below: export interface ConfigData { DB_NAME: string; } @Injectable() export class ConfigManager { private static _inst ...

Encountering an error when sending data from a React application to a Flask server: Unhandled Promise Rejection - Unexpected < token in

Despite looking through various responses on this forum, I'm still encountering the same issue. My JSON is properly formatted and does not contain any HTML tags. I've tried using double quotes instead of single quotes for 'Key', but it& ...

Retrieve and showcase Json data from two different nodes using Ajax

I'm struggling to show the data from json properly. The title displays correctly, but item.volumeInfo.industryIdentifiers.type is coming back as undefined. $.ajax({ url: 'https://www.googleapis.com/books/v1/volumes?q=:isbn=0-13-727827-6', d ...

JsPlumb: Incorrect endpoint drawn if the source `div` is a child of a `div` with `position:absolute`

My current setup involves two blue div elements connected by jsPlumb. You can view the setup here: https://jsfiddle.net/b6phv6dk/1/ The source div is nested within a third black div that is positioned 100px from the top using position: absolute;. It appe ...

Exploring ways to store session data in Next.js 13 with Supabase for seamless persistence

Encountering an issue with next-auth. Upon logging in, the result shows ({error: 'SessionRequired', status: 200, ok: true, url: null}), despite having an active session. The console also displays this error message, which I believe may be related ...

"Can you provide instructions on placing a span within an image

I am trying to figure out how to insert a <span> into an <image>, similar to the effect on the page . However, I do not want this effect to occur on hover(), but rather on click(). My goal is to insert "data-title" into the <span> and hav ...

Display with organized information, Arrange with unprocessed data in DataTables.net

Below is a snippet of the datatables configuration I am working with: { "dom" : "rltip", "processing" : true, "serverSide" : false, "order" : [ [ 1 , "desc" ] ], "searching" : false, data: [ { "column-a" : "Samp ...

Unmarshalling data with Jackson

I am working on a User interface: public interface User{ public static final String USER_KEY = "UK"; public String getSessionKey(); public List<Ties> getTies(); } There are two subclasses of User interface: abstract class UserKind1 imp ...

What is the best way to add both the id and the full object to an array list at the

Requirements: "admin-on-rest": "^1.3.3", "base64-js": "^1.2.1", "react": "^16.2.0", "react-dom": "^16.2.0" I have a User model that includes a List of Roles. // User { id: "abcd1234", name: "John Doe", ... authorities: [ { ...

Step by step guide to showcasing images dynamically in user interface

My current project involves displaying a screen with an HTML table and an image. The HTML table is fully dynamic. The Code Working Process When the user loads a page (with a URL), I render an HTML table in different parts as the page loads. I retrieve al ...

I am just starting to explore firebase and I'm having trouble organizing my data. I've attempted to use the query function and orderBy

After experimenting with query and orderBy() methods, I'm still struggling to properly integrate it into my code. Here's what I have so far: Methods: async saveMessage(){ try { const docRef = await addDoc(collection(db, "chat"), ...

I am looking to transfer the value of one textbox to another textbox within a dynamic creation of textboxes using JavaScript

var room = 1; function add_fields() { room=$('#row_count').val()-1; room++; var objTo = document.getElementById('education_fields'); var divtest = document.createElement("div"); divtest.setAttribute("class", "form- ...

Differences between React's useCallback and useMemo when handling JSX components

I have created a custom component called CardList: function CardList({ data = [], isLoading = false, ListHeaderComponent, ListEmptyComponent, ...props }) { const keyExtractor = useCallback(({ id }) => id, []); const renderItem = useCallba ...

What is preventing me from accessing the 'passport' fields within the JSON stored in the session?

I have a node application that utilizes express, socket.io 1.0, and passport. After a user successfully authenticates through passport-twitter, I store their information in a session store using the following code; var passportSocketIo = require("passport ...

Sophisticated filter - Conceal Ancestry

Check out this snippet of my HTML: <td> <a class="button" href="#"> <input id="download">...</input> </a> <a class="button" href="#"> <input id="downloadcsv">...</input> </a> </td> I am ...

How is it possible for my search results page to retrieve the words I input?

Currently, I am in the process of creating the search result page and I plan to utilize dynamic routing for implementation. Here is a snippet of my search bar code: <Link href={`/productSearchResult/${searchWord}`}> <a className={styles.navbar_s ...

Issues with Angular updating the *ngFor Loop

I'm looking to showcase a lineup of upcoming concerts in my HTML, sourced from a web API (which is functioning correctly). The API is encapsulated within a ConcertService: @Injectable({ providedIn: 'root' }) export class ConcertService { ...

Create a generic function that retrieves a specific property from an array of objects using the select method

Currently, I have implemented four functions that select entries from an array based on different properties. if ($scope.filters.filter1) $scope.filteredEntries = $scope.filteredEntries.filter(function (o) { return o.field1 === $scope.filt ...

transforming milliseconds into date format suitable for JQGrid styling

My Jqgrid is pulling data from a PHP file that returns JSON. The date constraint in the JSON is in milliseconds and I need to convert it to a regular date format. I have been searching for a solution and came across one that almost works: formatter:&apo ...