Encountered a problem parsing JSON data that begins with "var ..."

While attempting to retrieve a JSON file from a server, I encountered an issue. The JSON file contains the following data:

var reviews = [
    {
        "firstName":"Simon", 
        "lastName":"Lock",
        "fullName":"Simon Lock",
        "location":"San Francisco",
        "reviewTitle":"Super quality.. I will show here again!",
        "reviewBody":"Super nice quality, fast devilery, good prices. I will shop here again!",
        "starRating":"5"
    }, 
    {
        "firstName":"John", 
        "lastName":"Smith",
        "fullName":"John Smith",
        "location":"New York",
        "reviewTitle":"Princely Sum",
        "reviewBody":"A decent local curry house in Faversham, Kent known for its Elvis nights.",
        "starRating":"4"        
    },
];

As anticipated, an error occurred while retrieving the file using $.ajax:

SyntaxError: Unexpected token v 

Since it is not in valid JSON format, I attempted to use a different dataType. My inquiry is:

Is there a method to store that variable from the JSON file in another variable for normal manipulation?

I also tried utilizing FileReader(), but unfortunately it did not work for me.

Thank you

Answer №1

JSON serves as a method for data storage, distinct from JavaScript code. It is not equipped to process var reviews =. Your JSON file should solely contain the data, as shown below.

[
    {
        "firstName":"Anna", 
        "lastName":"Jones",
        "fullName":"Anna Jones",
        "location":"Los Angeles",
        "reviewTitle":"Incredible Service!",
        "reviewBody":"Outstanding customer service, quick delivery, unbeatable prices. I will definitely be a repeat customer!",
        "starRating":"5"
    }, 
    {
        "firstName":"David", 
        "lastName":"Brown",
        "fullName":"David Brown",
        "location":"Chicago",
        "reviewTitle":"Hidden Gem",
        "reviewBody":"A hidden gem of a cafe in downtown Chicago with amazing pastries.",
        "starRating":"4"        
    }
]

Answer №2

Keep in mind that in situations where security is of utmost importance, it is not advisable but you do have the choice to utilize the eval() function on the raw text of the document.

eval('var ratings = [
  {
    "firstName":"Emma", 
    "lastName":"Smith",
    "fullName":"Emma Smith",
    "location":"New York City", ...

will create a variable called reviews that holds the desired object.

Note: indeed eval is considered harmful, I am aware

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

Switch button - reveal/conceal details

I am looking for assistance in toggling the visibility of information when clicking on an arrow icon. I have attempted to use JavaScript, but it was unsuccessful. My goal is to hide the information below by clicking on the downward-facing arrow image , an ...

Using jQuery .css({}) is not causing negative margin to function as expected

$('#thankYouMessage').css({"height": textHeight, "margin-top:": "-52px", "padding-left": "19px"}); The CSS property 'padding-left:' will be applied as expected, but the negative margin will not take effect. The 'margin-top:' ...

Show the result of file upload, whether it was successful or not, using ReactJS

I need to implement an Ajax call for uploading a file to the server. I want to display success and failure messages based on the outcome of the file upload process. $.ajax({ url: "https:my_url", data: {my data: my_data}, method : "POST", success: ...

How to implement a file upload using AJAX in a Grails application within a g:

I am currently facing a challenge with uploading files via Ajax in a modal window form. I have tried various Grails plugins for ajax file upload but without success. Is there a way to achieve file upload without page refresh using the following code: &l ...

Manipulating datetime format within an input element of type date using Angular's ngModel

I have a date input in my form that is populated from the controller with a string value for 'dateOfDiagnosis'. The format of this string includes the time as well, like this: "2010-09-08T00:00:00" To bind this value to an input field in Angu ...

Uniform Fixed Width for Material UI Table Cells

Below is a Material UI Table with columns set to a fixed size of 205px each, and the table itself set to 100% width. However, when there isn't enough space available, the columns do not shrink according to the text inside them, remaining stuck at 205p ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

Why is `screen` important?

Recent articles in June 2020 discussing "how to utilize react testing library" often showcase a setup similar to the one below: import React from 'react'; import { render, screen } from '@testing-library/react'; import App from '. ...

html form submission error - please refresh

After submitting a form on my page, I keep encountering an error every time I try to refresh the page. I've attempted several solutions that I came across online, but none of them have resolved the issue as I continue to face this error on different ...

What is the best way to dynamically generate dependent dropdown lists in AngularJS?

Currently, I am involved in a project where I utilized the following link to populate specific dropdown menus. My goal is to have dynamically dependent dropdown lists that can be used as filters. While I came across some references for dependent dropdown l ...

Rendering color with a three.js image texture (loaded using ColladaLoader)

I just started learning three.js 2 days ago and I'm a bit of a newbie. After drawing a box on SketchUp, exporting it as a collada file (.dae), and loading it into a scene with three.js, I tried tiling the object with textures but unfortunately, I fai ...

Wait for the playwright to detect a specific and exact change in the inner text

There is a specific innerText that transitions from Loading to Play after 2-3 seconds. I want to wait for this change to happen before proceeding. Currently, I am using the following code snippet: let attempt = 0; let maxRetries = 4; let payerButtonStatus ...

When a div in jQuery is clicked, it binds an effect to a textbox that is

HTML: <div class="infoBox2 blackBoxHover"> <h2>Link: </h2> <input class="fileInput" type="text" id="linkText" name="linkText" /> </div> JAVASCRIPT: $('#linkText').parent('div').click(function () ...

Launching npm using the command "npm run protractor" results in console errors being thrown upon completing the test

Recently, we made the decision to streamline the installation process of Protractor on local machines by specifying it in package.json rather than installing it individually with the -g flag. The addition we made looks something like this: "scripts": { ...

AngularJS's support for html5mode on GitHub pages is now available

Is it feasible for GitHub pages to accommodate AngularJS in html5mode? I came across a source online suggesting that it can be done with a fallback page for 404 errors. However, this solution seems flawed as it may result in multiple 404 errors, which wou ...

The issue with 'this' not resolving correctly within a prototype method is causing unexpected behavior in the context of inheritance

I've created a constructor that extends a module in node.js called (https://github.com/fluxxu/evalidator). Within this extended constructor, I've defined two additional methods in the prototype, with **method B** calling method A using the ' ...

Javascript malfunctioning - exhausted all troubleshooting options

My JavaScript code consists of a single line, but I keep encountering the "getElementById null" error. document.getElementById("menu-background").style.left = "0"; HTML: <html> <head> <title></title> <link rel="style ...

Retrieving values from a multidimensional array in JavaScript

I need some help with my code. I am struggling to pass an array (larray3) containing elements from two other arrays (larray1 and larray2) from data.js to model.js and view.js. Despite correctly building the multidimensional array in data.js, when I receive ...

What is the method to retrieve an element within an array of objects?

I received a JSON response that appears as [object Object] within the data variable: { "name": "John Johnson", "street": "Oslo West 16", "posts": { "id1": "121331", "id2": "9089085", "id3": "3424234" } } The value ...

Direct the user to a webpage with the option for postback functionality or caching

I'm encountering an issue on my webforms site with 2 menus. When a button is clicked on a page, it triggers some C# events through a webservice (ajax) and then redirects to another page using history.go(-1). The problem arises when I create a session ...