Parsing JSON data on the client side in an ASP.NET application

I am currently working with JSON data that looks like this:

 "Table":[
 {
 "AF":2000.00
 "RegionNumber":1
 "RegionName":"Black Sea"
 },
 {
 "AF":100.00
 "RegionNumber":1
 "RegionName":"Black Sea"
 },
 {
 "AF":15000.00
 "RegionNumber":2
 "RegionName":"Istanbul"
 },
 {
 "AF":31000.00
 "RegionNumber":1
 "RegionName":"Black Sea"
 },
 {
 "AF":11000.00
 "RegionNumber":2
 "RegionName":"Istanbul"
 }
 ]

My goal is to reorganize the data using JavaScript into the following format:

series: [{
    name: 'Black Sea',
    data: [2000, 100, 31000],
    stack: 'Bookings'
}, {
    name: 'Istanbul',
    data: [15000,11000,0],
    stack: 'Bookings'
}]

Does anyone have suggestions on how I can achieve this transformation?

Answer №1

This code snippet comes close to meeting your requirements and leverages Ramda.js as well

const dataset =  {
    Table: [
        {
            AF: 2000,
            RegionName: "Black Sea",
            RegionNumber: 1
        },
        {
            AF: 100,
            RegionName: "Black Sea",
            RegionNumber: 1
        },
        {
            AF: 15000,
            RegionName: "Istanbul",
            RegionNumber: 2
        },
        {
            AF: 31000,
            RegionName: "Black Sea",
            RegionNumber: 1
        },
        {
            AF: 11000,
            RegionName: "Istanbul",
            RegionNumber: 2
        }
    ]
}

const transformTableData =
  R.pipe(
    R.groupBy(R.prop("RegionName")),
    R.map(R.pluck("AF")),
    R.toPairs,
    R.map(R.zipObj(["name", "data"])) 
  )

const transformData = (dataset) => ({
  series: transformTableData(dataset.Table)
})

console.log(transformData(dataset))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

Answer №2

If you're coding in pure JavaScript:

 let storage = {}
 for (let key in data) {
     let entry = data[key];
     if (storage[entry.Information] !== undefined) storage[entry.Information].content.push(entry.Value);
     else storage[entry.Information] = {
         type: entry.Information,
         content: [entry.Value],
         category: 'Books'
     }
 }

 let outcome = {
     types: []
 };

 for (let key in storage) {
     outcome.types.push(storage[key]);
 }

 console.log(outcome);

Answer №3

When working with web methods, I've successfully passed arrays of custom objects into List without any issues.

If you're encountering JSON formatting problems due to quotes around property names, try updating your object like this:

var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];

Then, adjust your data line to look like this:

data: JSON.stringify({ scores : scoresList }),      

I hope this suggestion resolves your issue...

UPDATE: Here's a functioning example...

<script type="text/javascript">
$(function () {

    var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];

    $.ajax({ type: "POST",
        url: "Tryouts.aspx/Test",
        data: JSON.stringify({ scores: scoresList }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response.d == true) {
                alert("success!!!!!");
            } else {
                alert("problem!!!!!!!!!");
            }
        },
        error: function (xhr) {
            alert("ERROR");
        }
    });

});
</script>

Below is the codebehind snippet :

public class Score
{    // default constructor    
    public Score() { }
    public int TraitID { get; set; }
    public double TraitScore { get; set; }
}

[WebMethod]
public static bool Test(List<Score> scores)
{
    return true;
}

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

Can you offer advice on creating jasmine tests for an Angular controller and service similar to this?

I've been struggling with this issue for hours, mainly because I'm still new to Jasmine and AngularJS. The problem lies within my controller. angular.module('toadlane.controllers', []). controller('MainController', functi ...

In Javascript, what significance does the symbol ":" hold?

While exploring the Ionic framework, I came across the following code snippet: import { AlertController } from 'ionic-angular'; export class MyPage { constructor(public alertCtrl: AlertController) { } I'm curious about the significanc ...

Error encountered in MVC 5: When using jQuery to assign a value to an object, the

Currently tackling a web development project as a newbie in the field and running into an issue with this snippet of code (which sets the end date to tomorrow if left blank): var date = new Date($('#txtStartDate').val()); var tomorrow = date.ge ...

The issue with Node module @kenjiuno/msgreader is that it is unable to find the constructor for MsgReader

I've been having trouble getting the example code for parsing Outlook .msg files using @kenjiuno/msgreader to work. Despite successfully installing the module with npm, my code doesn't seem to function as expected: const fs = require('fs&apo ...

Flutter: Iterating Through JSON Data

I am working on a Json parsing project using Flutter, and the structure of the Json data is as follows: { "Dependents":[ { "Name": "Kim", "Relationship": "Parent", "Entitlements": [ { "GP": { ...

trigger the focusout event within the focusin event

I am attempting to trigger the focusout event within the focusin event because I need to access the previous value from the focusin event, but the focusout event is being triggered multiple times. $('tr #edituser').focusin(function(){ var ...

Background image fixed with scrolling effect

I've been struggling with a parallax effect on my website. After seeing it work smoothly on other websites, I tried to implement it myself but couldn't quite get it right. The background image keeps moving when I scroll the page and I want it to ...

I am experiencing some difficulty with the GetServerDate using the JSON protocol in JQuery; it's

I am facing an issue while trying to execute a basic ajax call to fetch data from a file on a server. Even though I can access the file via the web browser and have diligently followed tutorials related to this topic, I have hit a dead end. Here is the sn ...

jQuery automatic slider for seamless transitions

I am in need of assistance with the coding for a website I'm currently constructing at www.diveintodesign.co.uk/ChrisMcCrone/index.html The coding being used is sourced from http://jquery.malsup.com/cycle/ The central large image functions as a slid ...

Issue with showing an input field following the button click

I'm having a bit of trouble with this function that should add an input element to a div. I've tried using appendChild and also concatenating the object to innerHTML, but no luck so far. Could it be something my beginner's mind is missing? f ...

Enhance jQuery dataTable with live updates from Firestore querySnapshot

Currently, I have implemented jQuery dataTable in my project to display data from Firestore. While everything seems to be working fine, an alert keeps popping up in the browser whenever there is an update in the Firestore data: DataTables warning: table i ...

The event for 'deviceready' in Cordova is not getting triggered when placed inside the angular .run block

Recently, I've been facing difficulties in getting 'deviceready' to register within AngularJS. It was functioning properly earlier, so I'm puzzled about what might have altered. If I trigger 'deviceready' from a global addEve ...

The datatables button triggers an event twice

Whenever I click a button or tag in datatables, the modal opens twice and ajax runs twice. PS. I am using angular.js with datatables as a directive that is created by jQuery datatables, not the Angular datatables module. How can I solve this issue? Than ...

Decoding whole numbers using JsonCpp

Currently, I am utilizing JsonCpp version 1.6.5 for the parsing of a JSON file that includes the following content: { "some-property" : 32 } Upon parsing, it appears that the type of the value is recognized as intValue instead of uintValue. I am curious ...

Converting a pandas column into a list for a JSON file transformation

How can I generate a JSON output file with one key containing a list from a DataFrame? Desired output: [ { "model": "xx", "id": 1, "name": "xyz", "categories": [1,2], }, { ...

Developing a new React application with Access Control List (ACL) and encountering an issue with Casl

I've recently started working with casl and it feels like I might be overlooking something crucial. So, I created a file named can.js which closely resembles the example provided in the documentation: import { createContext } from 'react'; i ...

The TextView is not displaying the Android Json data retrieved from mysqli

Currently, I am conducting a basic test to display JSON data fetched from PHP MySQLi in a TextView. TextView mTxtDisplay; String url = "http://192.168.1.102/web_service/test.php/"; @Override protected void onCreate(Bundle savedInstanceState) { super ...

Animating a mesh in three.js with color transitioning using tween.js

I've been struggling to accomplish this task. My goal is to change the color of a ConvexGeometry mesh when hovered over. So far, I can successfully change the mesh's color without any issues. The problem arises when I attempt to create a smooth ...

What could be causing the error message to appear stating that each list item must have a unique key when utilizing react-bootstrap in Nextjs?

My file currently contains keys for each child component, but it is still raising an error internally. I am unsure if I can resolve these issues on my own. export default function SecondaryNav(props:NavItems) { const router = us ...

What is the best method for converting an Object with 4 properties to an Object with only 3 properties?

I have a pair of objects: The first one is a role object with the following properties: Role { roleId: string; name: string; description: string; isModerator: string; } role = { roleId:"8e8be141-130d-4e5c-82d2-0a642d4b73e1", ...