Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

137
Views
Typescript classes deserialized json

I have 2 classes that represent a Tree structure as follows:

class Node {
        private _id: string;
        name: string;
        parent?: Node;
        children: Node[];
}

class Tree {
    root: Node;
    treeMap: Map<string, Node>;
}

I am writing a api GET /tree which should return tree json in the following manner:

[
    {
        "1": {
            "name": "root",
            "children": [
                {
                    "2": {
                        "name": "fish",
                        "children": [] // empty children
                    }
                },
                {
                    "3": {
                        "name": "bird",
                        "children": [ ...<any children>... ]
                    }
                }
            ]
        }
    }
]

when I do ctx.body = tree this is what the api returns:

{
    "root": {
        "_id": "1",
        "name": "root",
        "children": [
            {
                "_id": "2",
                "name": "fish",
                "children": []
            },
            {
                "_id": "3",
                "name": "bird",
                "children": []
            }
        ]
    },
    "treeNodeMap": {}
}

What would be the right way to convert it to the desired json format?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Have your classes implement toJSON() to produce the data structure you want.

// Define the data structure
interface SerialisedNode {
  [id: string]: {
    name: string;
    children: SerialisedNode[]
  }
}

class Node {
  private _id: string;
  name: string;
  parent?: Node;
  children: Node[];

  toJSON(): SerialisedNode {
    return {
      [ this._id ]: {
        name: this.name,
        children: this.children.map(node => node.toJSON())
      }
    }
  }
}

class Tree {
  root: Node;
  treeMap: Map<string, Node>;

  toJSON(): SerialisedNode {
    return this.root.toJSON();
  }
}

When your Tree (or any Node) is stringified as JSON, the transform will kick in and deliver the alternate data structure.

TypeScript Playground Demo

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!