Using JSON.parse to convert a JSON list into a JavaScript array is not functioning correctly

By utilizing this function, I am able to fetch a JSON list:

$(document).ready(function () { 
        var idContact = @ViewData["IdPhysique"];
        var Url = "/Accueil/DonneListeFonctionContact";
        $.getJSON(Url, { IdContact: idContact }, function (data) {  

        });

});

The obtained JSON data is as follows:

Now, my goal is to convert that JSON into an array, so I attempted the following:

$(document).ready(function () { 
        var idContact = @ViewData["IdPhysique"];
        var Url = "/Accueil/DonneListeFonctionContact";
        var jsonData = $.getJSON(Url, { IdContact: idContact }, function (data) {  

        });
        var jsonArray = JSON.parse(jsonData);
});

Unfortunately, an error is being displayed in the Google development tool:

Uncaught SyntaxError: Unexpected token o

Are there any alternative methods to achieve the desired outcome?

Answer №1

There is no need to manually parse the data as jQuery handles it for you and passes it to your callback function in the data argument. When using $.getJSON(), the JSON is not directly returned. Instead:

 $(document).ready(function () { 
    var idContact = @ViewData["IdPhysique"];
    var Url = "/Accueil/DonneListeFonctionContact";
    $.getJSON(Url, { IdContact: idContact }, function (data) {  
        // The data variable here is already an array due to jQuery's parsing
        // You can access its length property to perform checks
    });
 });

In addition, the JSON response displayed in your question is invalid. Property names and string values should be enclosed in double-quotes like so:

[{"IdFonction":734, "LibellFonction":"Clercs"}, ...

Answer №2

No need to use JSON.parse since the data is already in array format when received as JSON.

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

Cease execution of MySQL query upon clicking the stop button

I'm facing a problem that has me completely stuck. I've looked through numerous posts, but none of the information seems to be helpful in solving my issue. Therefore, I'm reaching out here once again, hoping that someone can provide assistan ...

Node.js Error: (Headers already sent, cannot be modified)

My goal in the program is to utilize both res.send and render simultaneously with the same data. I have a Qt application that can receive the data from my Node JS, but it appears challenging to send and render the data on the webpage at the same time. - ...

Exclude child rows from row count in DataTable

I have successfully implemented a feature on my datatable where child rows are toggled when a parent row is clicked. Here is the code I used: $(function() { $('tr.parent') .css("cursor","pointer") .attr("title","Click to expa ...

Attempting to display my ejs template from a node server following the activation of a delete button, all without utilizing ajax

I have created a basic blog application using node.js for the backend and ejs for the frontend. Posting blogs using a web form works well by calling a post route. Now, I am facing an issue with implementing a delete button for each blog post. The current s ...

`Incorporate numerous models into a For Loop for efficient processing`

Currently, my goal is to: Retrieve a JSON file from the server that contains data regarding my models Utilize a PLY loader within a for loop to incorporate them into the scene Include them in an array Below are the functions I've implemented: func ...

Easily toggle between different content within the same space using Twitter Bootstrap Tabs feature. Display the tabs

I made a modification to the bootstrab.js file by changing 'click' to 'hover': $(function () { $('body').on('hover.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) { e.p ...

Convert JSON objects into arrays with multiple dimensions

What is the best way to retrieve the Object[][] from a JSONObject? Below is the code snippet I am currently using to accomplish this task: Object[][] object2dArray= {{"String"},{315296487},{142736598.342},{"text"}}; JSONObject json = new JSONObject(); js ...

Accessing multiple nested objects in Javascript using a string as an object reference

One thing I am aware of is the ability to define an object reference from a string, such as this: obj['string'] This essentially translates to obj.string. My query arises when trying to extend this beyond the first object value. This is what I ...

In right-to-left mode, two items in Owl Carousel vanish while dragging or touching

When using owl carousel 2 with the RTL option, I encountered an issue where the carousel disappears when dragging/touching the last item (5 or 6 slides to the right, it disappears). I prefer not to use the loop option to workaround this. How can I resolve ...

What causes the high memory consumption of the 'readdirSync' method when handling directories with a large number of files?

Consider the NodeJS code snippet below: var fs = require('fs'); function toMb (byteVal) { return (byteVal / 1048576).toFixed(2); } console.log('Memory usage before "readdirSync" operation: ', toMb(process.memoryUsage()['heap ...

The Ajax request is malfunctioning when passing local variables as parameters

In my code behind, I have defined a webMethod like this: [System.Web.Services.WebMethod] public static string testCall(int qid, String answerContent) { log.Debug("this is call from jquery" + qid.ToString() + answerContent); ...

Tips for utilizing the selected option in the name attribute with Javascript or jQuery

I am looking to use the "selected" attribute in the option element based on the name attribute using JavaScript or jQuery. Essentially, I want the option with name="1" to be automatically selected when the page loads. I have attempted the following code, b ...

Assigning isolate scope property to ngSelect element's directive for the purpose of pre-selecting an option has proven to result in

Upon loading my page, the form is populated with values fetched from an http service. At the top of the form sits a custom directive, specifically a select box: .directive('categorySelectBox', function(){ return { restrict: "A", repla ...

The replace function fails to recognize Cyrillic characters when combined with the /b flag

Struggling with a persistent issue, I've noticed that my code works perfectly with Latin characters but fails to recognize Cyrillic characters when using jQuery. $('p').each(function() { var $this = $(this); $this.html($this.text().re ...

Bug Alert: Incompatibility between Angular $resource and PHP causing issues with Update and Delete functionalities

As a newcomer to both AngularJS and PHP, I have been struggling to find comprehensive documentation on using $resource to update records in a database. While I did come across a helpful tutorial here that covers most aspects of $resource usage, I am having ...

Is it possible to modify a variable within the readline function?

Can anyone help me figure out how to update the variable x within this function? const readline = require('readline'); const r1 = readline.createInterface({ input: process.stdin, terminal: false }); let x = 1; r1.on('line', fu ...

Identifying Changes in Form Values Using jQuery

I am facing a challenge with a dynamic form that needs to detect the field sequence properly. Below is my JavaScript file: var i = 1; $("a.add-line").click(function(){ $("div.items").append( $('<div>').attr('id',&ap ...

Customizing the output format of Ng Date Picker beyond the standard ISO-8601

Just to clarify, I'm talking about a specific DatePicker component that can be found at the following link: Although the DatePicker interface is user-friendly and visually appealing, I'm facing an issue with the way it outputs values. While ther ...

How can I effectively separate the impact of Next.js onChange from my onClick function?

The buttons in my code are not functioning properly unless I remove the onChange. Adding () to my functions inside onClick causes them to run on every keystroke. How can I resolve this issue? In order to post my question, I need to include some dummy text. ...

Utilizing local storage for the functionality of my Save Button

My innovative program features a drag-and-drop functionality for assigning players to different teams. If 'Player A' is dragged into the 'Team D' column, I am looking for ways to manipulate localStorage or any other function to save the ...