Issues encountered when parsing JSON data file

I'm facing an issue with reading a json file in JavaScript. I've tried the code below, but it generated an error: Uncaught SyntaxError: Unexpected token ':'

    <script>
    function loadJSON(callback) {   
      var xobj = new XMLHttpRequest();
      xobj.overrideMimeType("application/json");
      xobj.open('GET', 'weather.json', true);
      xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(JSON.parse(xobj.responseText));
        }
      };
    }

    //usage:
    loadJSON(function(json) {
      console.log(json); 
    });
    </script>

The json file I am trying to read contains this data:

{
   "RegionPK{region='kirovohrad', observation=6, forecast=12, level=100000.0}":{
      "temperatureStatistics":{
         "count":26,
         "sum":123.400146484375,
         "min":3.850006103515625,
         "max":6.75,
         "average":4.746159480168269
      },
      "humidityStatistics":{
         "count":26,
         "sum":1797.7999954223633,
         "min":56.599998474121094,
         "max":79.4000015258789,
         "average":69.1461536700909
      },
      "cloudnessStatistics":{
         "count":17,
         "sum":0.0,
         "min":0.0,
         "max":0.0,
         "average":0.0
      }
   },
   "RegionPK{region='dnipropetrovsk', observation=0, forecast=3, level=100000.0}":{
      "temperatureStatistics":{
         "count":46,
         "sum":90.8670654296875,
         "min":1.181884765625,
         "max":2.481903076171875,
         "average":1.975370987601902
      },
      "humidityStatistics":{
         "count":46,
         "sum":3598.199996948242,
         "min":72.0,
         "max":83.30000305175781,
         "average":78.22173906409222
      },
      "cloudnessStatistics":{
         "count":32,
         "sum":0.0,
         "min":0.0,
         "max":0.0,
         "average":0.0
      }
   }
}

The error is pointing at this section:

RegionPK{region='kirovohrad',observation=6,forecast=12,level=100000.0}":{
However, my file has passed json validation. Is there any way to read this file correctly or is my json file invalid?

Answer №1

It appears that the information you supplied is in JSON object format, but JSON.parse requires a JSON string as input to return a JSON object.

Based on the data provided, using

JSON.parse(JSON.stringify(jsonFile))
(where jsonFile represents the supplied data) results in a valid JSON object, indicating that there are no issues with the data as presented.

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

Obtain and utilize the background color to easily implement the same color in another window

For my Chrome Extension project, I am looking to retrieve the background color of the current page and then set the background color of a window to match. Can someone guide me on how to accomplish this using JavaScript (with or without jQuery), and if ne ...

Error: Validation issues detected in field functionality

My goal is to loop through a set of text fields and check if the user has input any values. However, I'm facing an issue where even though I have provided values in the text fields, it seems like they are empty. To better illustrate my problem, I have ...

Tips for successfully navigating through subdocumented array fields values

I have successfully developed a basic todo application using the MEAN stack (MongoDB, Express, Angular, Node). The backend part of the application, powered by Node.js, has been tested and confirmed to be functional using Postman as the REST API client. How ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

.NET API encounters issues with long JSON strings being shortened when returned

I have a stored procedure in SQL Server that generates JSON using FOR JSON. When I execute the procedure directly in SQL, it returns the JSON correctly and I can validate the output using tools like jsonlint. However, when the procedure is called from a .N ...

Issues arise when there is excessive tapping on an iPad while incorporating jQuery animate and scrollTop() commands

I am currently in the process of designing a user interface for a web application. The layout I have in mind is similar to what can be found here. $("#scroll-down").on("click", function() { thumbnails.stop(true, true).animate({ scrollTop: &apos ...

Checking if a div element contains a child with a specific class name using JavaScript

Okay, so here's the dilemma: Is there a way to use JavaScript to determine if a DIV has a specific classname? For instance, consider this sample HTML <div class="cart"></div>. This DIV would act as the parent, and JavaScript would dynamic ...

Determine the Placement of Bootstrap Popover by Utilizing SVG and Mouse Coordinates

Is there a way to dynamically reposition the popover that currently appears to the right of the Circle SVG? I would like to either base its position on the user's mouse click within the CircleSVG or move it to the exact center of the SVG, including bo ...

Navigate to a different directory within Cypress by utilizing the cy.exec() function

Dealing with cypress to execute a python script in another directory. However, it seems like the directory change is not functioning as expected. visitPythonProject() { cy.exec("cd /Users/**/Desktop/project/"); cy.exec("ls"); // thi ...

Using the json_encode/decode function to add data to a JSON field in an object within Laravel unexpectedly changes my array into an integer

I have a Class called "File" with a field named "file_history" that stores JSON data. In my Laravel CRUD operations, I want to add new JSON values to this field. For example, when creating a File object in the database, the initial file_history field may l ...

I just stumbled upon Jupyter and I'm curious - can I utilize Javascript and store it in the cloud?

Yesterday evening, I stumbled upon Jupyter and began using it alongside Python. It seems like an excellent tool for coding, something that I've been in need of, but I'm not sure if I can integrate JavaScript with it. I noticed there are npm packa ...

Incorporating dynamic data binding using AngularJS in a span tag

In my view, I am using this Angular expression: <span ng-if="{{list.StoreList ? (list.StoreList.length ' Products)' : '(0 Products)'}}"> </span> The purpose is to display the count of items in StoreList if there are any, ...

Tips on incorporating `.env.local` into a script in `package.json`

Within my /src directory, I have several files named .env.*: .env .env.local .env.staging The content of src/.env is as follows: REACT_APP_NODE_ENV=123 The content of src/.env.local is: REACT_APP_NODE_ENV=456. To address this, I decided to install ...

Refresh the Vue page only once after it is mounted

Users should only experience the page refreshing once upon visiting. However, if I add location.reload() within the mounted() function, it causes an infinite loop of page reloads. ...

What is the best way to add custom meta tags in html-webpack-plugin?

When using Webpack in conjunction with the html-webpack-plugin, I have a requirement to conditionally inject a <meta></meta> tag into the generated index.html file based on an environment variable. How can this be achieved? ...

Assign the colId to the pinnedBottomRowData property within Ag Grid

I'm facing an issue with displaying data in the pinned row within ag-Grid Vue 2. I am utilizing pinnedBottomRowData to supply data for the pinned row, but despite the pinned row being visible, it remains empty. The problem arises from using dot notati ...

Can you provide instructions on how to adjust the width of a form using a JavaScript script within a CSS file?

I am currently working on creating a form where individuals can input their email addresses to receive some information. My goal is to design one HTML file that will work seamlessly on both desktop and mobile views by adjusting the form width based on th ...

What is the best way to detect input events from the Stripe cardElement to determine if a card is invalid and then proceed to disable the button?

While my user fills out the form with order information and customer details, I ensure that the submit button remains disabled until all validations are met. The library being used for this purpose is express-validate. In addition to the current setup, I ...

Is it possible to detect inline elements that have been wrapped?

I am facing a challenge with displaying an indefinite amount of in-line elements. Depending on the width of the browser, some elements may shift to a new line. I am curious to know if it is possible to identify and isolate these rows of elements, or if the ...

Error: The variable "message" has not been defined. Please define it before displaying the welcome

While I was experimenting with my welcome message and attempting to convert it into an embed, I ended up rewriting the entire code to make it compatible. However, upon completion, I encountered the error message is not defined. var welcomePath = './ ...