Creating dynamic JSON with JavaScript is a powerful feature

I have been struggling to dynamically create a JSON object in JavaScript with a nested structure like this. Despite my attempts, I keep encountering errors due to the complexity of the nesting. Can someone please assist me in generating this JSON format?

    {
     "name": "flare",
     "children": [
       {
         "name": "analytics",
        "children": [
         {
           "name": "cluster",
           "children": [
      {"name": "AgglomerativeCluster", "size": 3938},
      {"name": "CommunityStructure", "size": 3812},
      {"name": "HierarchicalCluster", "size": 6714},
      {"name": "MergeEdge", "size": 743}
     ]
    },
    {
     "name": "graph",
     "children": [
      {"name": "BetweennessCentrality", "size": 3534},
      {"name": "LinkDistance", "size": 5731},
      {"name": "MaxFlowMinCut", "size": 7840},
      {"name": "ShortestPaths", "size": 5914},
      {"name": "SpanningTree", "size": 3416}
     ]
    },
    {
     "name": "optimization",
     "children": [
      {"name": "AspectRatioBanker", "size": 7074}
      ]
      }
     ]
    }
   ]}

This pattern repeats throughout the structure, creating a complex and intricate hierarchy. Any guidance on how to generate this type of JSON would be greatly appreciated.

Answer №1

Is this what you had in mind?

const result = [];
function parseJson(data) { 
    const obj = {
        "name": data.name            
    };
    data.find("children").each(() => {
        if (!obj.hasOwnProperty("children")) {
            obj.children = [];
        }
        obj.children.push(parseJson($(this)));
    });
    return obj;
}

$.each(input, (i, item) => {
  result.push(parseJson(input[i]));
});​

Finally, display the JSON with JSON.stringify(result)

Answer №2

To easily create each node, you can utilize the following function

function Node(element){
 $.extend(this, element);
 this.children = [];
 this.addChild = function(newElement){
   var newNode = new Node(newElement); 
  this.children.push(newNode);
  return newNode;
 }
}

Creating a dynamic tree is now simplified

var tree = new Node({});
tree
.addChild({name:'branch'})
.addChild({name:'data'})
.addChild({name:'category'})
.addChild({name: "LeafCluster", size: 1234})

You have the ability to add children to any node.

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

Is there a way to retrieve a List object from JSON rather than a LinkedHashMap?

I have a method that is supposed to retrieve different objects from JSON based on the class type provided as an argument. However, when I attempt to return a list of objects based on the argument, I only receive LinkedHashMaps in an ArrayList. Despite ext ...

Uncovering the secrets of navigating a JSON hierarchy

I'm trying to extract a specific value from this JSON data. My goal is to search by the State field, like 'NH', and retrieve the MaintenancePercentage and OfficePercentage values. Despite attempting to iterate through payrollDefaults.State ...

Using MySQL's JSON_OBJECT() function with certain fields pre-populated with JSON strings

What is the best way to retrieve a JSON_OBJECT() containing 3 columns, where some of them already contain a JSON format string? For example, in this query the info field holds a json string, resulting in the entire object being escaped: SELECT T1.id ...

What is the most efficient way to extract JSON data from a list and transform it into columns in Python?

I have received JSON data from Amazon, including various sales metrics and information. After using json_normalize to convert the data into a dataframe, I encountered an error while attempting to flatten the nested list in one of the columns. Here is a sni ...

Collect all chosen items within a form along with their concealed inputs in preparation for submission

Imagine a scenario where you have a table filled with polaroid pictures and you are tasked with deciding whether to keep or discard each one. Yes signifies keeping it, while No indicates throwing it away. I am looking to create an element for each photo t ...

Secure authentication in Windows Communication Foundation using HTTPS

I am currently working with a WCF service that utilizes https for communication and json for response format. In order to secure my methods, I decided to switch the authentication in IIS from anonymous & basic to just basic. However, after making this cha ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Using JavaScript to validate birth date selection along with three drop down menus in ASP.Net

Currently, I have implemented a functionality using three drop down controls to prompt users to select their birth date. In order to validate the selected date, I have incorporated JavaScript code in all three drop down "onChange" events. The function is ...

Rendering nested JSON using React Native

After successfully loading a JSON object and storing it in this.state, I am encountering difficulty accessing nested levels beyond the initial level. Here is an example of the JSON file being used: { "timestamp": 1530703572, "trend": { "value": 0, ...

How can I create a customizable grid in ext4 designer that can be manipulated remotely?

How can I create a grid in ext designer that receives its column definition through a remote json query? ...

What is the process for linking an HTML document to another HTML document within a div using jQuery?

Check out my HTML code: <!DOCTYPE html> <html> <head> <title>Hilarious Jokes!</title> <meta charset="utf-8"> <link href="final%20project.css" rel="stylesheet"> <script src=" ...

Using React to fetch data and then mapping it inside a function

I am facing an issue where I need to make a request for each item in the MAP, but I want to ensure that I wait for the response before moving on to the next object. Currently, my code is sending out all the requests simultaneously, causing the Backend to c ...

Converting an object into Json format

I'm encountering an issue while trying to convert an object into Json format. The error message I am receiving from the code snippet below states "An instance of type string cannot be assigned to a variable of type JsonResult". Can someone please help ...

Yet another interactive JQuery feature found within the JQuery UI Tabs framework, utilizing seamless Ajax page loading

Currently, I am using JQuery U Tabs with Ajax Page Calls. In my Pages, I have a custom scroller that is functioning correctly. Additionally, I have an ajax search table that works when the page is loaded by itself in the browser but not when called within ...

Struggling with populating a table in MVC using Ajax/Json

I am struggling to retrieve the top 10 most recently submitted forms associated with specific userids. My AJAX function is not working as expected when populating my table. During debugging, it captures the button click event and passes it to AJAX, but th ...

The synopsis cannot be displayed by the RottenTomatoes API

I'm having some trouble with the RottenTomatoes movies API. I've been trying to display the movie's synopsis below the input field, but it's not working as expected. Can anyone point out what might be causing the issue here? If you nee ...

"Assigning an array as a value to an object key when detecting duplicates in a

Let's assume the table I'm iterating through looks like this: https://i.stack.imgur.com/HAPrJ.png I want to convert each unique value in the second column into an object, where one of the keys will hold all values from corresponding rows. Here& ...

What is the best approach for resolving this asynchronous task sequencing issue in JavaScript?

Below is a code snippet where tasks are defined as an object and the function definition should ensure the expected output is met. Let tasks = { ‘a’: { job: function(finish){ setTimeout(() => { ...

Image Filter: Only Display Selected Images, Not All

I have designed a Filter Image Gallery where all images are initially displayed when the page loads. There are four different tabs available - Show all, Nature, Cars, and People. However, I want to change this default behavior so that only Nature filter i ...

Iterate through an array while only mapping X number of elements during each iteration

Currently, I am working on a project that involves creating a grid of client logos using Tailwind CSS, react, and GSAP. The paths to the client logos are fetched from a JSON file. Since the list of client logos is quite lengthy, I decided it would be inter ...