Error encountered: Unexpected 'o' token in JSON parsing

Although this issue has been discussed numerous times before, I am struggling to identify the error in my code. The error message I am receiving is 'Uncaught SyntaxError: Unexpected token o'

Below is the ajax code I am using:

$.ajax({
    type: "POST",
    url: "json-http-server.aspx/GetDoctors",
    data: '',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: myFunction,
    failure: function (response) {
    alert("AJAX error");
}
});

Here is the function responsible for parsing the returned data:

function myFunction(response) {
    var arr = JSON && JSON.parse(response) || $.parseJSON(response);
    var out = "";
    out += "<table border='1'>";
    out += "<tr><th>Title</th>";
    out += "<th>Name</th>";
    out += "<th>Gender</th>";
    out += "<th>Address</th>";
    out += "<th>Hospital</th></tr>";
    for (var i = 0; i < arr.length; i++) {
        out += "<tr>";
        out += "<td>";
        out += arr[i].Title;
        out += "</td>";
        out += "<td>";
        out += arr[i].Name;
        out += "</td>";
        out += "<td>";
        out += arr[i].Gender;
        out += "</td>";
        out += "<td>";
        out += arr[i].Address;
        out += "</td>";
        out += "<td>";
        out += arr[i].Hospital;
        out += "</td>";
        out += "</tr>";
    }
    out += "</table>";
    document.getElementById("OutputDiv").innerHTML = out;
}

Below is the JSON data returned from a webservice:

'[{
    "Title":"Univ. Prof. Dr.",
    "Name":"John",
    "Gender":"Doe", 
    "Address":"Washington DC, USA",
    "Hospital":"Washington General Hospital"
  },
  {
    "Title":"Univ. Prof. Dr.",
    "Name":"Billy",
    "Gender":"Joe",
    "Address":"California, USA",
    "Hospital":"AKH Univ-Kl.f.Innere Med. II"
  },
  {
    "Title":"Univ. Prof. Dr.",
    "Name":"Alex",
    "Gender":"Haize",
    "Address":"Michigan, 2500, USA",
    "Hospital":"Rheuma-SKA Baden der SVA der gew. Wirtschaft"
}]'

Answer №1

 let data = JSON && JSON.parse(result) || $.parseJSON(result);

It's important to note that the JSON data was already parsed before the result variable was assigned a value.

(jQuery handles this automatically when you specify dataType: 'json' in your code, which you have done, or when the server identifies the response as JSON).

By converting it to a string ("[object Object]") and then attempting to parse that string as JSON, you are creating unnecessary confusion.

It is best to eliminate that particular line of code.

Answer №2

Looks like there's a syntax error in your JSON data. You're missing commas (,) between } and {.

Here's the fixed version:

'[{
    "Title":"Univ. Prof. Dr.",
    "Name":"John",
    "Gender":"Doe", 
    "Address":"Washington DC, USA",
    "Hospital":"Washington General Hospital"
  },
  {
    "Title":"Univ. Prof. Dr.",
    "Name":"Billy",
    "Gender":"Joe",
    "Address":"California, USA",
    "Hospital":"AKH Univ-Kl.f.Innere Med. II"
  },
  {
    "Title":"Univ. Prof. Dr.",
    "Name":"Alex",
    "Gender":"Haize",
    "Address":"Michigan, 2500, USA",
    "Hospital":"Rheuma-SKA Baden der SVA der gew. Wirtschaft"
}]'

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

Python's nested if conditions allow for more complex conditions to be

In a specific scenario, I am required to validate certain conditions within the provided JSON data and then take action accordingly. You can view the json data here. The condition that needs to be checked is as follows: Iterate through the JSON and ident ...

The MUI makeStyles() class has been implemented, yet the styles are not being displayed when using classList.add('class-name')

Currently, I am utilizing MUI makeStyles() to create a series of CSS classes. Within these classes, I am dynamically including and excluding one specific class to my Box element during file drag-and-drop events. The class is successfully added, as I can o ...

Using Javascript to organize an array of objects based on a specific condition

Having an array of objects structured as follows: obj = [{'name': 'Tom', 'age': 17, 'gender': 'male', 'color':'red', 'position':3}, {'name': 'Sam', ...

Unidentified entity triggering an error in the console

It seemed like there wasn't anything quite like this before... at least not that I could understand with my limited experience. I was experimenting with creating a global object that contains methods, including instructions for handling AJAX requests ...

Incorporating middleware in Next.js to remove route protection

Looking to remove the protection for the login page, and here is how my folder structure looks: https://i.stack.imgur.com/klPYV.png This is the middleware I am using: import { NextResponse, NextRequest } from "next/server"; export async functi ...

Guide to sequentially playing multiple video objects with buffering

As I work on developing a reference player application that utilizes node.js, javascript, and HTML5, I have encountered an issue. Currently, my player successfully loads a single video and generates diagnostic data from it. However, I am striving to enhanc ...

Open a web browser and continuously monitor the updates by using the `tail

Currently, I have developed a Python script that continually monitors a logfile for modifications (similar to the tail -f command) and showcases it on a console. I am interested in accessing the Python script's output through a web browser. What tools ...

A guide to serializing declarative links using Jersey and Jackson

In my project, I have implemented declarative linking. The configuration for my Jackson mapper is as follows: final ObjectMapper mapper = new ObjectMapper(); mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); mapper.configure(MapperFea ...

Updating HTML Pages with Dynamic Content

Dealing with a massive project consisting of 50,000 pages (20,000 aspx forms, 10,000 asp forms, and 10,000 html pages) can be overwhelming. With only 2 days to complete the task of adding content after the body tag on all pages, I am seeking advice on ho ...

Trigger an alert after a separate function is completed with jQuery

On my page, I have a function that changes the color of an element. I want to trigger an alert once this action is complete using changecolor(). However, I am unable to modify the changecolor() function due to certain restrictions. Is there a way to dete ...

When a user clicks on the div, it expands in size and then returns to

I developed a small quiz, where clicking on an answer moves the checkmark to the clicked div. const answers = document.getElementsByClassName('answer'); [].forEach.call(answers, function(answer) { $(answer).click(function() { if (!answer ...

Adjusting element position while scrolling

Objective The goal is to have the page navigation display lower on the page by default. This will provide a cleaner layout as shown in the image below. Context An interactive element for navigation was implemented utilizing Headroom.js. This library d ...

Efficient JSON parsing with Python's ijson module - diving into

Working on parsing a JSON web response with a specific format: [ { "type": "0","key1": 3, "key2": 5}, { "type": "1","key3": "a", "key4": "b"}, { &q ...

I am having trouble getting the color, metalness, lights, and shaders to work properly in Three JS on my

I attempted to create a simple code using Three.js for a red colored torus with a point light and a textured surface, but unfortunately, all I achieved was a black torus that rotates. It seems like the elements in this code are not functioning as expecte ...

Ways to showcase JSON data with jQuery

My code displays movie data from a JSON variable and populates it on a dropdown list based on the selected city. I aim to include show timings along with other details from the JSON content. The code snippet is as follows: $(document).ready(function() ...

Create a dynamic animation of an image expanding and shifting towards the center of its parent container

Is it possible to animate an SVG image within a div to grow to 80% screen height and move to the center of the parent div when a specific function is called? If so, how can this be achieved? function openNav(){ $("#topnav").animate({height:'100%& ...

Verify and deselect boxes

Can someone help me with checking and unchecking checkboxes? I'm facing a lot of issues with it. You can find my code snippet here: http://jsfiddle.net/N5Swt/: <input type="checkbox" id="checkbox1" /> <span> Check me! </span> // ...

What is the best way to match my JSON data to a POJO based on the JSON values?

After creating a Java POJO class from an XSD file using JAXB, I now have JSON data. How can I efficiently map my JSON values to the corresponding attributes in the POJO class? Any suggestions would be much appreciated. Thanks! ...

Errors have been observed when using JavaScript variables that begin with the symbol $

For the longest time, I've used JavaScript variable names that begin with $ to signify that they hold jQuery values. For example: $buttons = $( 'button' ); However, a couple of nights ago, I encountered an issue when loading the page in the ...

Obtaining a result from a Promise in AngularJS

Here is a snippet of an Angular JS Service that I have: 'use strict'; app.factory('loggedService', ['$http', 'authService', 'customerService', function ($http, authService, customerService) { var out = ...