From Linq query to dynamic d3.js visualization

I am searching for an effective method to input data from my MVC application into a d3.js bubble chart. Specifically, the standard bubble chart requires nested data in this format:

{
    "name": "flare",
    "children": [
        {
            "name": "analytics",
            "children": [
                {
                    "name": "cluster",
                    "children": [
                        {
                            "name": "CNN",
                            "size": 3938
                        }
                    ]
                },
                {
                    "name": "graph",
                    "children": [
                        {
                            "name": "MTV",
                            "size": 3534
                        }
                    ]
                }
            ]
        }
    ]
}

On the server side, I have a linq query accessing a SQL database:

var results = from a in db.Durations
                          where a.Category == "watch"
                          group a by a.Description
                              into g
                              select new
                              {
                                  name = g.Key,
                                  size = g.Select(d => new{d.Begin, d.End}).Sum(d => SqlFunctions.DateDiff("hh", d.Begin, d.End))
                              };

            return Json(results, JsonRequestBehavior.AllowGet);

This linq query result, represented as Json, appears like this:

[{"name":"CNN","size":1950},{"name":"MTV","size":1680}]

I am unsure of the best approach to format and create the required nested structure using my query results.

  1. Utilize anonymous types on the server-side
  2. Adjust the linq-query on the server-side
  3. Apply d3.js nest on the client-side
  4. Implement a simpler bubble model if the nested structure is unnecessary
  5. Explore alternative methods beyond options 1-4

Any suggestions or advice would be greatly appreciated.

Answer №1

Swap out your return statement with this one.

return Json(new
    {
        title = "Websites",
        items = results
    },
    JsonRequestBehavior.AllowGet);

This will result in the following output:

{
  "title": "Websites",
  "items": [
    {
      "title": "Google",
      "views": 5000
    },
    {
      "title": "Facebook",
      "views": 3200
    }
  ]
}

For instance, if each website had an additional string Category property, with categories like "Search" or "Social Media", you can proceed as shown below.

return Json(new
    {
        title = "Websites",
        items = results.GroupBy(site => site.Category).Select(group => new
        {
            title = group.Key,
            items = group
        }
    },
    JsonRequestBehavior.AllowGet);

That would generate something similar to:

{
  "title": "Websites",
  "items": [
    {
      "title": "Search",
      "items": [
        {
          "title": "Google",
          "views": 5000
        },
        {
          "title": "Bing",
          "views": 4000
        }
      ]
    },
    {
      "title": "Social Media",
      "items": [
        {
          "title": "Facebook",
          "views": 3200
        },
        {
          "title": "Twitter",
          "views": 2800
        }
      ]
    }
  ]
}

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

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

How to encode images into base64 format in a C# HTML file

I am working with an html file and I need to convert the images from local source to base64 using C#. <img width=83 height=100 src="Untitled_files/image001.png" alt="cid:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4128 ...

How can one ensure efficient execution of heavy JavaScript tasks without causing any blocking issues?

Currently, I'm utilizing webgl to load a 3D model and running some code to manipulate it before displaying it. The issue is that this process takes several seconds and completely restricts the user from performing any other tasks during that time. It ...

Create a shape using the fabric.js library that resembles a polygon

I am attempting to create a custom polygon using the following code snippet: http://jsfiddle.net/e5Xth/3/ canvas.on('mouse:move', function (options) { if (lines[0] !== null && drawingObject.type == "roof") { setStarti ...

Assigned a gender to my _id using the first name and last name

Hello, I am attempting to generate an _id in mongodb using a combination of the first name and last name. However, I'm encountering a problem with this process. My desired format for the id is like this: '_id':'midoxnavas' where &a ...

Regular expressions can be used to validate input that is a combination of alphanumeric characters and numbers, excluding any alphabetic characters

I need a regular expression in JavaScript that allows alphanumeric characters, as well as only numbers, spaces, and periods. Allowed: Hello Mr. 3367 6576567 55 3432 abc 3333333 ending in...4454 Not Allowed: Hello Mr. Khan One Two Three ABCSDS ...

Unable to remove Object ID from an array using Mongoose

How can I successfully remove a logged-in user's objectId from an array field named interest in my project model? Project Model Schema: const projectSchema = new mongoose.Schema({ // Define the schema fields here }) The Route to Remove Interest: ...

"Enhance your database with Firebase's dynamic features for adding and removing

Within my firebase database, I have the following data structure: -ActionSheet -PendingApproval -SomeKey1 -someData -someData -someData -SomeKey2 -someData -someData ...

The function Array.Clear() is not functioning properly with the given parameters of name, 0

I am facing an issue with resetting a string array that I have declared as follows: string[] strA9 = new string[64]; Even after using the array, when I try to reset all elements back to null using the code below: Array.Clear(strA9, 0, strA9.Length); It ...

Using jQuery to toggle an open and close button

My icon functions as an open/close button. When opened, it turns red and rotates 45 degrees. The issue arises when trying to close it. Changing the div class causes the icon to disappear while in its active state. Below is the jQuery code I am using: $(". ...

Moving an array in AngularJS from one file to another

As someone new to AngularJS, I am facing an issue with integrating two separate files that contain modules. Each file works fine individually - allowing me to perform operations on arrays of names. However, when switching views, the arrays remain stored un ...

Executing a function in Node.js upon completion of another function

After the completion of my "app.get('/news/api/:newsName', function(req, res)" method, I want to call my "app.get('/news/news-desc', (req, res)" method. My code looks like this: let articleUrlArray = []; app.get('/news/api/:ne ...

"Error encountered while attempting to write an incompatible data type to JSON (NSConcreteData

I encountered an issue while using AFNetworking to post an audio file along with some data. The exception I received is as follows: *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON wr ...

Navigating through each item in a JSON file with robotframework and extracting specific ones based on a query

I am currently working on extracting a specific node from a JSON file based on another node in the same element. To clarify, I need to retrieve the names of all students in the JSON sample provided below who are marked as "certified":"false". Sample JSON { ...

JavaScript is failing to capture the value of undefined when retrieving data from

It seems like there's a clear oversight on my part. All I'm trying to do is check for undefined. Despite using what I believe are all possible ways to check for undefined in the script pictured, it still manages to bypass all the checks and goes ...

Unraveling the mysteries of MongoDB: Unleashing the power of querying and aggreg

Within my mongoDB collection, I have 3 Json documents as follows: { 'title': 'Best', 'array' : [ {'name' : '1', 'value': '2' }, {'name' ...

Ways to fix the error message stating: "TypeError: Unable to retrieve the 'total' property

Having trouble resolving an issue with my code. I keep getting this error message: angular.js:14328 TypeError: Cannot read property 'total' of undefined Every time I try to run a search query, this error pops up. The data.php file is properly ...

Tips for iterating within a Vue.js template without disrupting the HTML structure

Currently, I am attempting to implement a loop within a table. However, I have encountered an issue with the following code: <tr v-for="( block , index ) in listRenderBlock" :key="index"> <div v-for="( section , i ) in ...

Unauthorized access using Sails JS with Passport - error code 401

Trying to secure my sails js rest api using the passport http package, but struggling to pinpoint the error in my code. Utilized this repository and this tutorial for guidance on implementation. The issue I'm facing is consistently receiving a 401 sta ...

response cannot be generated outside of the db.query function

router.get('/details/(:id)', (req, res) => { let vehicle_base; db.query("select b.name, count(b.name) AS total_vehicles from base AS b, vehicle AS v where b.id = v.base_id AND b.fleet_id = " + req.params.id , function(err, result){ ...