Leveraging JSON.stringify alongside getter/setter in TypeScript

In my TypeScript code, I am utilizing getter/setter accessors. To differentiate between variables and methods with the same name, I have adopted the convention of prefixing the variable with a lower dash, as shown in many examples:

private _major: number;

get major(): number {
  return this._major;
}
set major(major: number) {
  this._major = major;
}

When I use JSON.stringify() to convert the object into a JSON string, it uses the variable name (_major) as the key.

I prefer not to have all keys prefixed with a lower dash in the JSON output file. Is there a way for TypeScript to utilize the name of the getter method as the key instead? Or are there other techniques to maintain clean JSON output while still using getter/setter methods?

Although I am aware of manual approaches to modify JSON keys before generating the output string, I am interested in finding a simpler solution.

Here is a JSFiddle that showcases the current behavior.

Answer №1

Unfortunately, using the getter/setter name instead of the property name with JSON.stringify is not possible.

One workaround is to create a method like this:

class AppInfo {
    private _appId: number;

    get appId(): number {
        return this._appId;
    }

    set appId(appId: number) {
        this._appId = appId;
    }

    toJsonString(): string {
        let jsonString = JSON.stringify(this);
        Object.keys(this).filter(key => key[0] === "_").forEach(key => {
            jsonString = jsonString.replace(key, key.substring(1));
        });

        return jsonString;
    }
}

let app = new AppInfo();
app.appId = 12345;
console.log(app.toJsonString()); // {"appId":12345}

Answer №2

After trying out @Jan-Aagaard's method, I decided to test this implementation:

public convertToJSON(): string {
    let obj = Object.assign(this);
    let keys = Object.keys(this.constructor.prototype);
    obj.convertToJSON = undefined;
    return JSON.stringify(obj, keys);
}

This code snippet is designed for utilizing the convertToJSON function.

Answer №3

In my opinion, directly iterating through the properties and manipulating strings can be risky. Instead, I prefer utilizing the prototype of the object itself. Here's an example of how you can achieve this:

public static convertToStringJSON() : string {
    return JSON.stringify(this, Object.keys(this.constructor.prototype)); // assuming 'this' refers to the version class
}

Answer №4

A recent project of mine led me to develop a compact library called ts-typed, aimed at generating getter and setter functions for runtime type checking. During this process, I encountered an issue with JSON.stringify() and resolved it by introducing a custom serializer. To streamline the serialization process, I also proposed incorporating a toString method (similar to Java's) under the name toJSON.

For instance:

import { TypedSerializer } from 'ts-typed';

export class RuntimeTypedClass {
    private _major: number;

    get major(): number {
       return this._major;
    }

    set major(major: number) {
       this._major = major;
    }
    /**
    * The toJSON method acts as a toString equivalent, simplifying property access.
    *
    */
    toJSON(): RuntimeTypedClass {
        return TypedSerializer.serialize(this);
    }
}

Answer №5

An innovative solution for handling getter/setter methods in situations where private fields are not explicitly defined or named differently. By utilizing Object.getOwnPropertyDescriptors, we can extract the get methods from the prototype.

In order to make the object compatible with JSON.stringify, a custom toJSON function is added to perform a shallow clone using Object.assign(...). Care is taken to avoid an infinite loop by excluding JSON.stringify() calls within the toJSON method and removing any _private fields for cleanliness.

public toJSON(): any {

    let clone: any = Object.assign({}, this); 

    const descriptors = Object.getOwnPropertyDescriptors(Object.getPrototypeOf(this))

    Object.keys(descriptors).forEach(key => {
        if (descriptors[key] && descriptors[key].get) {

            delete clone[key];
            clone[key] = this[key]; 
        }
    });

    Object.keys(clone).forEach(key => {
        if (key.indexOf('_') == 0) {
            delete clone[key];
        }
    });

    return clone;
}

Answer №6

This solution may not be dynamic, but it gets the job done

export class MyClass{
     text: string

     get html() {
         return this.text.toString().split("\n").map(e => `<p>${e}</p>`).join('');
     }

     toJson(): string {
         return JSON.stringify({ ...this, html: this.html })
     }
}

When using this code snippet

console.log(myClassObject.toJson())

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

How to Transform a String into a Map in Flutter

Currently, I am utilizing SQFlite for local data storage. Within my table, there is a field named 'json' which is of type TEXT and stores JSON data as a String representation, like so: '{name: Eduardo, Age: 23, Sex: male}'. Everything ...

Can jq handle synchronous functions?

The usage of jq.run('.', '/path/to/file.json').then(console.log) appears to be causing asynchronous behavior, leading to the output being displayed as Promise { <pending> }. This delay in obtaining the result is problematic, promp ...

An unexpected issue occurred while converting XML data into JSON format

I have been using a piece of code that converts XML to JSON: // Converting XML to JSON var XmlToJson = function xmlToJson(xml) { //console.log('called xmltojson'); //console.log(xml); // Creating the return object var self = this ...

TypeScript: manipulating generics T and U

Currently, I am in the process of developing a library with the following API structure: export var reduce = <T, U>( tArray: T[], tReducer: (current: U, tItem: T, index: number, tArray: T[]) => U, options: IChunkifyOptions = DEFAULT_OPTIONS ...

JavaScript for fetching JSON data

Hey everyone, I've been working on implementing user login functionality. When a user submits their login credentials, an API call is made using AJAX. Depending on whether the login credentials are correct or incorrect, I receive a response that gets ...

Retrieve the specific object's methods based on a specified return type criteria

Initially, I have a class containing attributes and methods. My goal is to filter and retrieve only the keys of the methods. I created a utility type for this purpose and it worked smoothly: type FunctionPropertyNames<T> = { [K in keyof T]: T[K] e ...

Adding the "@" symbol as part of an object name in JSON using PHP

Need to generate JSON using PHP with certain content { "@context":"something", "type":"something" } Decided to create a custom class class doc { public $context; public $type; } Unfortunately, the JSON output does not include the @ si ...

Unable to retrieve string value for JSON key

Currently, I am delving into the world of manipulating JSON data in Java and encountering an issue with the use of getString method for one of the keys. Let me share the code snippet with you: public static void getJSON(String matchID){ String s = ""; ...

Updating the function type definition in TypeScript after importing it into a separate file

I have created a unique hook named useDropdownSelection. It's a straightforward one. Take a look at the code below: import { useState } from 'react' export const useDropdownSelection = (initialValue: string) => { const [selectedOption, ...

Error message: Missing required parameter when updating customer information via the Shopify API

Hello, I am encountering an issue while trying to update a customer in my system. The error message I keep receiving is: Required parameter missing. Could you please provide any insights on what might be causing this error or if there are any issues with ...

How can I display images stored locally within a JSON file in a React Native application?

Hey everyone, I'm currently facing an issue with linking a local image from my images folder within my JSON data. Despite trying various methods, it doesn't seem to be working as expected. [ { "id": 1, "author": "Virginia Woolf", " ...

" Jquery.ajax, PHP, and the case of the mysteriously missing response

I've been struggling to create my first universal code for handling ajax responses. Unfortunately, I haven't been able to see any output either in PHP or in the ajax response. There must be something missing in the post data. Below is the ajax r ...

Whenever I try to execute 'docker build --no-cache -t chat-server .', I always encounter type errors

Below is the Dockerfile located in the root directory of my express server: FROM node:18 WORKDIR /usr/src/server COPY package*.json ./ RUN npm install COPY . . EXPOSE 3000 RUN npm run build CMD ["npm", "start"] Here is the contents of my .dockerign ...

Is there a way to validate an input field and display error messages using a TypeScript file instead of directly in the HTML file within Angular 4?

I am just starting out with Angular, so please bear with me if my question seems basic. I'm eager to learn and hopeful that I can find the answers I need here. Currently, I have implemented validation for an input field that captures a user's Fi ...

Obtaining the count of a specific column in Angular 6 by grouping objects based on the same value in an array

In TypeScript, I have an array of objects and I am using a foreach loop. The array contains 2 columns with a progress value of 100, while the rest have values less than 100. My goal is to calculate the count of columns with a progress value of 100, which ...

Angular5+ Error: Unable to retrieve summary for RouterOutlet directive due to illegal state

When attempting to build my Angular App using ng build --prod --aot, I consistently encounter the following error: ERROR in : Illegal state: Could not load the summary for directive RouterOutlet in C:/Path-To-Project/node_modules/@angular/Router/router.d. ...

What is the best way to send JSON data to a web service using PHP?

Our team is currently utilizing a web service that handles JSON payloads for sending and receiving responses. While we have successfully implemented this functionality in C#, we are facing challenges when trying to achieve the same in PHP. Could you prov ...

Generate several JSON files containing two lists utilizing iteration loops

Can anyone guide me on how to create multiple JSON files with two lists? Let's say I have the following input: animal_list = ["cat", "dog", "bird", "fish", "chicken", "tiger"] name_file = [&q ...

Leveraging code behind and serialized JSON in an ASP.NET web application

I've recently created an array using a LINQ query: var aTimeResultQuery = (from fct in context.fct_testautomation join dr in context.dim_driver on fct.driver_key equals dr.driver_key join tc in context.dim_test_case on fct.test_case_ ...

An issue has occurred: Unable to access the 'seatsavailable' property of an undefined object

Currently, I am immersed in a project involving Angular 6 and utilizing the @Input and @Output decorators. In this scenario, I have the Bookride Component functioning as the parent component with RideDetails serving as the child component. Successfully tra ...