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

Mapping data visually

Currently, I am in the midst of a vuejs project where I aim to create data visualizations on a map. My goal is to showcase a world map with percentages representing each country. However, I find myself at a loss on how to begin this task. Are there any r ...

Using the jq command, you can easily append data to an array at a specific index

I'm currently working on updating specific key values within a particular array element using jq. The JSON structure I have is as follows: [ { "name":"element1", "properties":{ "hardwareProfil ...

Having trouble deciding between JSON, XML, or using a database?

As I work on developing an app that involves sending an id and receiving a JSON node from PHP, I am considering the best approach for storing my data. Should I keep it as a static PHP array as shown in the code below, or should I save the data to an exte ...

Angular2 Service Failing to Return Expected Value

It's frustrating that my services are not functioning properly. Despite spending the last two days scouring Stack Overflow for solutions, I haven't been able to find a solution that matches my specific issue. Here is a snippet of my Service.ts c ...

Ensure that the <TabPanel> content occupies the entire width and height of its parent container

Currently, I am working with React and material-ui. Specifically, I am utilizing an appbar with tabs and my goal is to have the content of each tab expand to full width and height when selected. If you'd like to see an example, check out this sandbox ...

When running `grunt serve: dist`, an error is thrown stating: "Unknown provider: utilProvider <- util <- NavbarController"

I am facing a problem with my angularJS website that is built using the yeoman angular-fullstack generator. When I run grunt serve, everything works perfectly fine. However, when I try to run grunt serve:dist, I encounter this error: grunt serve: dist -&g ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

Intermittently play a series of sound files, with only the final sound ringing out

My goal is to create an app that plays a sound based on a number input. I have several short MP3 audio files for different numbers, and I want the app to play these sounds in sequence. However, when I try to do this, only the last sound corresponding to th ...

Tips for transferring POST body data to a different route without losing any information

Assuming I have the following route: app.post('/category',function(req,res){ res.redirect('/category/item'); }) In this scenario, the user will submit data to the '/category' route and then automatically be redirected ...

Extract CSS from Chrome developer tools and convert it into a JavaScript object

Recently, we have started incorporating styles into our React components using the makeStyles hook from Material-UI. Instead of traditional CSS, we are now using JavaScript objects to define styles. An example of this is shown below: const useStyles = ma ...

Dealing with a frustrating roadblock in Three.js where you encounter an "Unknown format" error while trying to work with

Greetings, I am relatively new to THREE.js and currently experimenting with loading a .FBX Object using the FBXLoader found in three/examples/jsm/loaders/FBXLoader while integrating this into React.js. Upon launching the page, I encountered an issue where ...

Each sub-array must be assigned a unique parent array name in the JSON structure

Flutter / Dart Discussion I have an array with an "Accessories" list that includes a brand name ("samsung"). I need to add the brand name to all subarrays. In the subarray of the "Brand" key, you can see the second code space which contains the parent ke ...

Display the name of the file on the screen

Is there a way to dynamically display the file name in a view instead of hardcoding it? I would appreciate any assistance. Thank you! Here is my code snippet: <li> @if (Model.Picture2 != null) { base2 = Convert.ToBase64String(Model.Pict ...

Exploring the differences in performance between React hooks and React classes

Currently, I am delving into understanding React hooks and could use some assistance with comprehending whether every time a React function renders, the hook state resets. Below is a brief example related to fixing a header on scroll: class Header extends ...

Utilizing variable query operators solely in instances where they hold value

Imagine you are on a movie website where you can customize filters for the movies displayed to you. Currently, these preferences are stored in the User model as a map. Here is an example of what the preferences object might look like: preferences: { yea ...

Issues with JQuery .attr method not functioning as expected

I'm having trouble with the .attr() function in jQuery. It doesn't seem to be changing the background-color of the div with the id "outline" like I expected. Here's an example of my code: <div id="outline"></div> And here is t ...

The Next Js API is experiencing difficulties resolving

I'm just starting out with back-end development so I could use some assistance with my current project. I am working on a next.js application that applies a black and white filter to an image when it is uploaded. In the index.js file, once a file is s ...

Reading Json file and sending the value using the Dashing Meter

How can I successfully send a value to a Dashing meter from a JSON file using Ruby? require 'json' file = File.open('/mnt/json/process1.json') contents = file.read SCHEDULER.every '2s' do contents["poolused"] = { label ...

Exploring the integration of Stripe Checkout with React and Express.js

Seeking assistance with integrating Stripe Checkout into my React application. I need to create a route in my nodejs/express server that will provide the session id required for setting up Stripe Checkout on the front end. The aim is to redirect users to s ...

What could be causing the version error when running 'pip install json'?

When attempting to install 'pip install json' in my command prompt, I encountered an error - ERROR: Could not find a version that satisfies the requirement json (from versions: none) ERROR: No matching distribution found for json. What steps shou ...