Transforming a typical JSON file into a parent-child hierarchical JSON structure similar to the one utilized in d3's flare.json file format

My JSON file has a specific structure:

{
    "a": "b",
    "c": "d",
    "e": {
      "f": "g",
      "h": "i"
    }
  }
  

I want to transform it into the following structure:

{
    "name": "Root",
    "parent": "null",
    "children": [
      {
        "name": "a",
        "parent": "Root",
        "children": [
          {
            "name": "b",
            "parent": "a"
          }
        ]
      },
      {
        "name": "c",
        "parent": "Root",
        "children": [
          {
            "name": "d",
            "parent": "d"
          }
        ]
      },
      {
        "name": "e",
        "parent": "Root",
        "children": [
          {
             "name": "f",
             "parent": "e",
             "children": [
               {
                  "name": "g",
                  "parent": "f"
                },
                {
                  "name": "h",
                  "parent": "e",
                  "children": [
                     {
                       "name": "i",
                       "parent": "h"
                     }
                ]
              }
            ]
          }
        ]
      }
    ]
  }

To create a collapsible-tree diagram, I need a clear parent-children hierarchy relationship in my JSON file. Apologies for any issues with the indentation.

Answer №1

If you want to achieve the desired style using the Root element, one approach is to implement a recursive solution that involves an object and a parent value.

In order to obtain the expected format with the Root element, you must provide a new object that adheres to the same structure as the inner objects within the given data.

{
    Root: data[0]
}

const
    getObjects = (o, parent) =>
        o && typeof o === 'object'
            ? Object.entries(o).map(([name, v]) => ({ name, parent, children: getObjects(v, name) }))
            : [{ name: o, parent }];

var data = [{ a: "b", c: "d", e: { f: "g", h: "i" } }],
    result = getObjects({ Root: data[0] }, 'null');

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

Consider the following approach:

const treeify = (orig) => Object.entries(orig).map(
  ([k, v]) => (Object.assign({name: k}, typeof v == 'object'
    ? {children: treeify(v)} 
    : {children: {name: v}}
  ))
)
const convert = (orig) => ({name: 'Root', children: treeify(orig)})

const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}}

console.log(convert(orig))

treeify is responsible for the main processing, while convert serves as a simple wrapper that introduces the Root node. It's worth noting that this implementation doesn't involve creating parent nodes, as indicated in the comments.

Revision

After reviewing Nina Scholz's concise answer, which incorporates parent nodes (despite my initial assumption of its complexity), I propose an alternative version that also includes them. Although the absence of parents was acceptable, I find this updated version of convert preferable:

const treeify = (orig, parent) => Object.entries(orig).map(
  ([k, v]) => (Object.assign({name: k, parent}, typeof v == 'object' 
    ? {children: treeify(v, k)} 
    : {children: {name: v, parent: k}}
  ))
)

const convert = (orig) => treeify({Root: orig}, 'null')[0]

const orig = {"a": "b", "c": "d", "e": {"f": "g", "h": "i"}}
console.log(convert(orig))

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

encountering difficulties when trying to install npm packages in node.js

Starting out with Node.js and new to installing packages like express.js and underscore.js using NPM. However, every time I attempt to install using the following commands: npm install express, npm install underscore I keep encountering errors. Please ...

Combining one item from an Array Class into a new array using Typescript

I have an array class called DocumentItemSelection with the syntax: new Array<DocumentItemSelection>. My goal is to extract only the documentNumber class member and store it in another Array<string>, while keeping the same order intact. Is th ...

Converting Java String to JSONObject in Android: Troubleshooting JSONP issue

Here is the code snippet I am working with: String json = request.excutePost("http://192.168.1.42:3000/login_client",urlParameters); JSONObject jsonObj = new JSONObject(json); The error displayed in logCat is as follows: org.json.JSONException: Value ...

substitute a component with a different one if it is present

I'm currently working on a script that will automatically replace one element with another as soon as it is created, even when the page loads. Despite my attempts to use MutationObserver, I haven't been successful. var target = document.querySe ...

React's useEffect delay instability

Currently, I am in the process of creating a Pomodoro clock. My approach involves utilizing the useEffect and setTimeout functions to develop countdowns. Initially, everything appeared to be running smoothly until I noticed a delay ranging from 30ms to 50m ...

Storing Python Query Results: Best Practices

Context: I've developed a Python application for tracking the status of various tools. These tools send their data from specific runs, all of which are stored in an Oracle database as JSON files. Challenge/Solution: Instead of repeatedly querying th ...

Expanding the size of the number input in Twitter Bootstrap to accommodate changing content dimensions

I have a numeric input field that I want to customize in terms of width. I need the field to start with a minimum width so that -1, the default value, fits nicely inside. As the value changes, whether decreasing to -100 or increasing to -1,000 and beyond ...

Mastering the art of properly connecting Angular HttpPromise

Recently, I encountered an angular Service containing a crucial function: service.getItemByID = function(id) { var hp = $http({method: "GET", url: "service/open/item/id", headers: {"token": $rootScope.user.token}, para ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Managing the state of forms using NGRX and @Effects

After submitting a form and triggering an action that is caught by an effect for an http call, I am curious about how to handle the following scenarios upon completion or failure: Display a success message once the action finishes Reset all fields for fu ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

Plunker fails to run simple AngularJS demo

I'm having trouble figuring out why this basic example isn't functioning as expected on Plunker. http://plnkr.co/edit/EfNxzzQhAb8xAcFZGKm3?p=preview var app = angular.module("App",[]); var Controller = function($scope){ $scope.message ="Hel ...

Issues with the Winston transport for Loggly are causing inconsistent performance

I have implemented Winston with 3 transports: Console, File, and Loggly (using https://github.com/loggly/winston-loggly-bulk). While the Console and File transports are functioning properly, I am facing an issue with the Loggly transport. It only logs my ...

Angular2: Ensuring Sequential Execution Line by Line - A Comprehensive Guide

I have a designed an Angular2 Navbar Component that features a logout button: import { Component, OnInit } from '@angular/core'; import { LoginService } from '../login.service'; import { Router } from '@angular/router'; @Co ...

There seems to be an issue with the accurate calculation of the screen width while utilizing the scrollbar-gutter

Please take note: The scrollbar-gutter: stable; property is not compatible with Safari. Additionally, the issue seems to be specific to Chrome and works fine in Firefox. I have observed some unusual behavior when attempting to position elements fixed to t ...

How can I use an HTML button to activate a function that inserts text into a read-only text-box?

Trying to write a simple piece of HTML code that finds the number greater than or equal to the first initial amount that wholly divides the second given amount. The code attempts to divide the numbers, and if it fails, increments the first number by 1 and ...

Styling the content within Template Strings is not supported by VSCode

Recently, I've noticed that there are two scenarios in which my VSCode doesn't properly style the content within my template strings. One is when I'm writing CSS in a JavaScript file, and the other is when I'm fetching data from GraphQL ...

Wordpress tabs with dynamic content

I came across a code on webdeveloper.com by Mitya that had loading content tabs and needed the page to refresh after clicking the tab button. It worked perfectly fine outside of WordPress, but when I tried implementing it into my custom theme file, it didn ...

Are you struggling to differentiate between a JSON array and a JSON object?

{ error: false -booking: [2] -0: { booking_id: 32 booking_user_id: 25 booking_service_id: 1 booking_date: "2015-10-01 12:16:48" booking_completion_date: "0000-00-00 00:00:00" booking_ ...

Leveraging trustAsHTML with an array of object elements

I'm facing a challenge in passing an array of objects from an Angular Controller to the ng-repeat directive. The objects within the array have multiple properties, some of which may contain HTML that needs to be displayed using the ng-repeat. I' ...