Ajax is able to fetch a JSON string, however it struggles to iterate through the successful data as an

My current project involves creating a graph using d3.js. I came across some php code that fits my needs perfectly. However, I am working with c# and Visual Studio, so I need to convert it into asp.net. For starters, I want to input some hardcoded sample data and generate an image using d3.js, along with incorporating JavaScript code from the php project. I now have a server-side web method that returns a JSON string. The parameter 'dataSample' is of type Dictionary and there are no errors in sight.

The backend code looks like this:

return JsonConvert.SerializeObject(dataSample);

On the frontend, I am utilizing AJAX to fetch this data.

<script>
$.ajax({
    type: 'POST',
    url: 'Map.aspx/read_data',
    contentType: 'application/json; charset=utf-8',
    data: "{ }",
    dataType: "json",
    success: function(response) {
        d3.json("", function (data) {    
            graph.data = response.d;
            drawGraph();
        });
    },
    error: function(error) {
        console.log("Oops! Something went wrong!");
    }
});
</script>

The AJAX call is successful, and the Console log displays the graph.data obtained from the response:

{"DSO":{"name":"DSO","type":"group0","depends":["BPR","Transmission Company","Government"],"dependedOnBy":["TSO","Transmission Company"],"docs":""},"TSO":{"name":"TSO","type":"group1","depends":["BPR","DSO","Producer Secondary Energy","Government"],"dependedOnBy":["Producer Secondary Energy"],"docs":""}}

Next, I aim to loop through each JSON object so that the drawGraph() function can create nodes for each one. For instance:

for (var name in graph.data) {
    var obj = graph.data[name];
    console.log("name: " + name + "object: " + obj);
}

The issue arises when the console output does not display each object in the JSON correctly. Instead of individual objects, it seems to be looping through every letter.

The incorrect console log output can be viewed https://i.sstatic.net/fBDZK.png.

I'm striving to output the complete object instead of the current behavior.

Answer №1

To iterate through JSON data, it is important to first parse the JSON object and then use a proper for loop to access its elements.

<script>
        $.ajax({
            type: 'POST',
            url: 'Map.aspx/read_data',
            contentType: 'application/json; charset=utf-8',
            data: "{ }",
            success: function(response) {
                parsedData = jQuery.parseJSON(response);
                // Implement your for loop logic here
            },
            error: function(error) {
                console.log("Oops! Something went wrong.");
            }
        });
    </script>

Answer №2

Just like @shilly pointed out, it appears that you are iterating through a JSON object...
To simplify your code, consider the following solution:

let jsonData = JSON.parse(dataGraph);

for (let key in jsonData) {
    let value = jsonData[key];
    console.log("key: " + key + " value: " + value);
}

Answer №3

To work with the data, you need to parse the string using JSON.parse and then iterate through the resulting JSON object.

For instance:

<script>
var data = JSON.parse('{"DSO":{"name":"DSO","type":"group0","depends":["BPR","Transmission Company","Government"],"dependedOnBy":["TSO","Transmission Company"],"docs":""},"TSO":{"name":"TSO","type":"group1","depends":["BPR","DSO","Producer Secondary Energy","Government"],"dependedOnBy":["Producer Secondary Energy"],"docs":""}}');

for (var key in data) {
     for (var property in data[key]) {
            console.log(data[key]['name']);
    }

}       
</script>

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

In order to apply a filter express within an array, make sure to utilize variables that

In my Express endpoint, I have various variables that may or may not be present. Depending on the presence of these variables, I need to execute a filter function on an array and apply rules from the req.body. Is there a way to include if conditions withi ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

Pass a selected object to a dropdown/select change event using AngularJS

Plunkr : http://plnkr.co/edit/BRQ3I4hFTlgKq4Shz19v?p=preview I'm attempting to pass the selected item from a dropdown to a function within my controller. Unfortunately, I keep receiving it as undefined. HTML : <!DOCTYPE html> <html> ...

Manipulating multiple variables in an array through jQuery and JSON response using $.each method

Here is my approach to generating a JSON response using PHP: foreach($results as $row){ $result['address'][] = $row['name']; $result['office_id'][] = $row['office_id']; } echo json_encode($re ...

Access the file and execute JavaScript code concurrently

Can I simultaneously link to a file as noticias.php and call a JavaScript function? <a href="javascript:toggleDiv('novidades');" class="linktriangulo"></a> The toggleDiv function in my noticias.php file: function toggleDiv(divId) { ...

Sending dynamic data through AJAX to a CodeIgniter controller is a common task that allows for seamless

Can anyone help me with retrieving data from a looping form in CodeIgniter? The form works fine, but I'm struggling to fetch the looping data in the controller. Here's my view (form): <form action="#" id="ap_data"> <div class="table-r ...

What is the best way to showcase the properties of multiple files with the help of

I have been attempting to utilize jQuery to exhibit the specifics of several uploaded files. Below is my code: <!DOCTYPE html> <html> <head> <title>jQuery Multi File Upload</title> </head> <body> <f ...

Getting started with a project using meteor.js and vue.js

As a beginner in meteor.js, I am eager to create a project using both meteor.js and vue.js. However, I am struggling to find the right method for managing files in meteor.js. Could someone please assist me by providing a demo project or video link that c ...

Manipulating a dynamic array within an Angular repeater using the splice method

Encountering an issue with deleting an object from an array using splice. The array, dynamically created through a UI, is stored in $scope.productAttributes.Products. Here's an example of the array structure... [ { "ProductLabel":"Net", "Code ...

What are the different ways to interact with the object retrieved from the onloadedmetadata event

Having trouble accessing a specific value in an object that is the result of the onloadedmetadata event. When I log the entire object using audioDuration, I am able to see and retrieve the respective value without any issues. However, when I try to access ...

Is it possible to include personalized titles on a website using AJAX and hashbang (#!) URLs?

Currently, I am utilizing an ajax-powered WordPress theme that features hashbang URLs such as www.example.com/#!/page. My main concern is whether or not it is possible to add custom titles and descriptions for each individual page in order to improve SEO. ...

Using Jquery Regex to Validate Numeric Range Input on KeyUp Event in an Input Field

I have been spending quite a few hours attempting to figure out a solution for this issue, but unfortunately, I haven't had much success. My goal is to add a Keyup/KeyPress event that only allows values between 2 and 1827. I am using an aspx inputbox ...

Paper.js: Is there a way to prevent canvas height and width from changing when the window is resized?

My canvas with paperjs is set up to resize dynamically when the window is resized. I appreciate any help in advance. HTML <canvas id="myCanvas" height="800" width="1000"></canvas> JS var Initialize = function () { var canvas = document ...

When using json_decode, be aware that it may convert lengthy numbers into scientific

Is there a way to prevent JSON from turning the trackingNumber into scientific notation when using json_decode? I want to access the data as an array without compromising the integer or rounding it. Can I loop through the RAW JSON without decoding it to ac ...

Struggling with implementing Angular and TypeScript in this particular method

I'm dealing with a code snippet that looks like this: myMethod(data: any, layerId: string, dataSubstrings): void { someObject.on('click', function(e) { this.api.getSomething(a).subscribe((result: any) => { // ERROR CALL 1. It ...

add a JavaScript variable to a JSON data structure

My JSON object is valid and it's called list_to_book_for: {"fold1-key1":{"name":"Van Antwerpen"},"fold2-key2":{"name":"Delporte"},"fold3-key3":{"name":"Lallemand"}} In order to add the content of a variable into this object, I have the following str ...

What's causing these divs to be misaligned in various directions?

I am currently working with a front-end framework based on flexbox called Material-UI, and I have noticed that the layout of certain components, particularly the quantity control elements, appears to be different even though they all share the same styling ...

Transmit JSON data using Autobahn Python

I am attempting to use sendMessage to send the json content from a URL to a client. def broadcast(self): response = urllib2.urlopen('http://example.com/json?as_text=1') data = json.load(response) for c in self.clients: c.sendMessage( ...

Map on leaflet with popup next to key

I am facing a scenario where I have a map with a unique legend that is styled either as an SVG or a PNG. The legend is always positioned in the bottom left corner but can be quite large, as users have the option to toggle it on and off. Additionally, the ...

Using jQuery AJAX to Populate a Textbox and Dropdown Menu

I am new to using JQuery AJAX, so I am still learning the syntax. Currently, I am retrieving values from a database and populating a dropdown box. What I would like AJAX to do is fill in three other fields with hardcoded information when a selection is mad ...