Creating a JSON file from a custom key-value class in Typescript: A comprehensive guide

I am struggling to find an npm package or create my own function that can generate a JSON file from elements within this specific class:

export class TranslatedFileElement {
    private key: string
    private hasChild: boolean                   
    private value?: string                      
    private values?: TranslatedFileElement[]    
    private isTranslated?: boolean

    public constructor() {
        this.key = '',
        this.hasChild = false,
        this.value = '',
        this.values = null,
        this.isTranslated = false
    }

    public setTranslateFileElement(
        _key: string,
        _value: string,
        _values: TranslatedFileElement[],
        _hasChild: boolean,
        _isTranslated: boolean
    ) {
        this.key = _key
        this.value = _value
        this.values = _values
        this.hasChild = _hasChild,
        this.isTranslated = _isTranslated
    }

    public setKey(_key: string) {
        this.key = _key
    }

    [...] //Other get's and set's
}

I have attempted a solution similar to the following code snippet, but it is not functioning correctly and seems to be causing more issues than solving:

private converter(elementsToJSON: TranslatedFileElement[], nestedLevel: number = 0): string {
    let JSONResult =  '{'
    elementsToJSON.forEach((element) => {
      JSONResult = JSONResult + '"' + element.getKey() + '" : '
      if (element.getHasChild()) {
        JSONResult = JSONResult + 
          this.converter(element.getValues(), nestedLevel + 2)
      } else {
        JSONResult = JSONResult + '"' + element.getValue() + '",'
      }
    })
    JSONResult =  JSONResult + '},'
    JSONResult = JSON.parse(JSON.stringify(JSONResult));
    return JSONResult
  }

Does anyone know of a reliable npm package or have a simple idea to help me solve this issue?

Answer №1

To achieve the desired outcome, I recommend implementing a method that can convert this structure into an object with the same format as the required JSON. You can then utilize the JSON.stringify function on the newly created object.

class TransformedFileElement {
...
    public toSerializedJSON(){
        return JSON.stringify(this.toRegularObject());
    }
    public toRegularObject(){
        let value:any=null;
        
        if (this.hasChildren){
            const reducer = (accumulator:any, currentValue:any) => ({...accumulator,...currentValue});
            if (this.values)
                value = this.values.map((child:TransformedFileElement)=>child.toRegularObject()).reduce(reducer,{});
            
        } else {
            value = this.data;
            
        }
        return {[this.identifier]:value};
    }
...
}

Answer №2

To easily convert the elements to JSON, you just need to use the following line of code:

JSON.stringify(elementsToJSON);

This will effectively translate the class properties into a JSON format.

The only potential issue arises if your data structure is not a traditional tree and contains cycles within it.

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

Accessing Key-Value Pairs in PHP from a JSON Encoded Array

Is there a way for me to retrieve the LocalId Key Value in Php? This particular Array is Json Encoded. {"0":{"kind":"identitytoolkit#VerifyPasswordResponse","localId":"u0iuiF09idQ1pEl0oJTfElqTtXr1"}} ...

Issue with Angular filtering when utilizing pipe and mapping the response

Code snippet from shop.service.ts getProducts(brandId?: number, typeId?: number) { let params = new HttpParams(); if (brandId){ params = params.append('brandId', brandId.toString()); } if (typeId){ params = params.append('typeId', ...

Error in Laravel due to incorrect UTF-8 character encoding is causing issues

When attempting to retrieve a list of all directories and include that list in a JSON response, an error is encountered indicating that the response contains malformed UTF-8 characters. The presence of letters such as "Æ Ø Å" in the directories is causi ...

Leverage ngFor to loop through a "highly intricate" data structure

In my project, I have stored data in a JSON file structured as follows: { "name": { "source1": ____, "source2": ____, "source3": ____ }, "xcoord": { "source1": ____, "source2": ____, "source3": _ ...

The scope attribute is not functioning as expected in the loopback model

After utilizing an "include" : "organization" query within the context of my request.json file, a related model, I noticed that the resulting output from the query does not include the intended relation. The structure of the model (request.json file) is ...

Can the JSON values be arranged in order?

I have a JSON list containing country names and codes. response = '{"ContainsErrors":false,"Result":[{"Name":"Aegypten","IsoCode":"EG"},{"Name":"Aequatorialguinea","IsoCode":"GQ"},{"Name":"Aethiopien","IsoCode":"ET"},{"Name":"Afghanistan","IsoCode":" ...

Classify JavaScript Array Elements based on their Value

Organize array items in JavaScript based on their values If you have a JSON object similar to the following: [ { prNumber: 20000401, text: 'foo' }, { prNumber: 20000402, text: 'bar' }, { prNumber: 2000040 ...

Generate a JSON file using the elements within the array

Here is an example of an array: var Device = { 'iPhone 6 Plus-Simulator-iOS 8.0': 'iPhone 6 Plus (8.0 Simulator)', 'iPhone 6-Simulator-iOS 8.0': 'iPhone 6 (8.0 Simulator)', 'iPhone 5s-Simulator-iOS 8.0&ap ...

How to reference 'this' within a d3 callback when using Angular 7

In an Angular directive, I am trying to access a class-level variable inside a callback function. To achieve this, I used an arrow function but the 'this' keyword is still not pointing to the directive. this.itemRects.selectAll('rect') ...

The success of an Angular function hinges on the outcome of an asynchronous function

Scenario: In my code, I have a function named isAuthorized() in a singleton called AuthSessionSingleton. This function depends on the result of an asynchronous operation. The async operation is an API call triggered in the constructor, expecting an objec ...

Importing components in real-time to generate static sites

My website has a dynamic page structure with each page having its unique content using various components. During the build process, I am statically pre-rendering the pages using Next.js' static site generation. To manage component population, I have ...

The FormData object appears to be blank, even though it was supposed to be populated when attempting to send a PDF file using a multipart FormData POST request in Cypress

I am attempting to send a PDF file as a POST request. The API supports the use of @RequestPart and @RequestParam: @RequestPart("file") MultipartFile file; @RequestParam(value = "document-types", required = false) Set<String> documentTypes; My appro ...

Making @types compatible with TypeScript 2.1 in Visual Studio 2015 Update 3

The potential of TS 2.x @types is intriguing, but I'm struggling to make it work effectively! I'm using Visual Studio 2015 - version 14.0.25431.01 Update 3 My TypeScript version for Visual Studio 2015 is 2.1.4, downloaded from this link The VS ...

Accessing router params in Angular2 from outside the router-outlet

I am currently working on a dashboard application that includes a treeview component listing various content nodes, along with a dashboard-edit component that displays editable content based on the selected branch of the tree. For example, the tree struct ...

Is there a way to specifically select the input field that the user has typed into using a selector?

Is it possible to use javascript/jquery to specifically target the input field that a user has just typed in? ...

Steps to resolve the 'Cannot assign value to userInfo$ property of [object Object] that only has getter' issue in Angular

I am currently in the process of building a web application using NGXS, and I'm encountering a specific error that I'm trying to troubleshoot. The issue arises when I attempt to fetch data from an API and display it within a column on the page. D ...

An issue occurred with Ionic 4: TypeError - Unable to access property 'name' as it is undefined

None of the answers to similar questions have provided a solution for me SITUATION: I've been setting up a SQL Server connection from my Ionic app. You can check out my previous question for more details The workflow goes as follows: Ionic connects ...

Restricting a checkbox to a maximum of 5 checkmarks

In a multi-column table, each column is represented by a checkmark. I want to limit the ability to tick a checkmark to only 5 checkmarks. Here is the code that has been implemented: <tbody> <ng-container *ngFor="let col of testData" ...

Developing a bespoke React Typescript button with a custom design and implementing an onClick event function

Currently, I am in the process of developing a custom button component for a React Typescript project utilizing React Hooks and Styled components. // Button.tsx import React, { MouseEvent } from "react"; import styled from "styled-components"; export int ...

Create a jQuery script that generates clickable links when a user is mentioned in the

Hey there, I've been incorporating this fantastic plugin created by Hawkee into my project. It functions similarly to Twitter, allowing users to @mention others. However, I'm encountering issues with the output when using the following method: u ...