What is the best way to implement custom serialization for Date types in JSON.stringify()?

class MyClass {
  myString: string;
  myDate: Date;
}

function foo() {
  const myClassArray: MyClass[] = ....
  return JSON.stringify(myClassArray); // or expressApp.status(200).json(myClassArray);
}

foo will generate a JSON string with the date format of YYYY-MM-DDThh:mm:ssZ.

I am interested in customizing the serialization process for the myDate property when using JSON.stringify().

If altering how JSON.stringify() works is not feasible, I am open to exploring other serialization libraries that might offer more customization options. Perhaps a library implementing a decorator pattern could help achieve this? Or maybe there is a native solution available?

Answer №1

Utilize the replacer parameter and define a function to achieve this functionality. Here is a simple example:

const data = [{
    date: new Date(),
    id: 1
  },
  {
    date: new Date(),
    id: 2
}]

const originalData = JSON.stringify(data)
const transformedData = JSON.stringify(data, replacer('date'))

function replacer(target) {
  return function(key, value) {
    if (key == target) {
      const month = new Date(value).getMonth()
      return `Date month: ${month}`
    }
    return value
  }
}

// [{"date":"2020-03-20T19:13:11.594Z","id":1},{"date":"2020-03-20T19:13:11.594Z","id":2}]
console.log(originalData)

// [{"date":"Date month: 2","id":1},{"date":"Date month: 2","id":2}]
console.log(transformedData)

Update

If you have any suggestions for improving my TypeScript decorator skills, please share them.

Here's an example of using a decorator:

@transformDate
class MyClass {
  date: Date;
  id: number;

  constructor(date, id) {
    this.date = date;
    this.id = id;
  }
}

function transformDate(target: any) {
  const formatted = new Intl.DateTimeFormat("en", {
    year: "numeric",
    month: "short",
    day: "2-digit"
  }).format(this.date);

  target.prototype.toJSON = function() {
    return {
      ...this,
      date: formatted
    };
  };

  return target;
}

const newData = [new MyClass(new Date(), 1), new MyClass(new Date(), 2)];

// [{"date":"Mar 20, 2020","id":1},{"date":"Mar 20, 2020","id":2}]
console.log(JSON.stringify(newData));

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

div maintain aspect ratio while scaling

My current layout is structured like this: HTML <div id="container"> <div id="zoomBox"> <div class="box"></div> <div class="box"></div> <div class= ...

Using the data from two input fields, an ajax request is triggered to dynamically populate the jQuery autocomplete feature

I've been struggling with this issue for quite some time now. My goal is to pass 2 arguments (the values of 2 input fields in a form) in my ajax call so I can use them for a jQuery autocomplete feature (the search is based on a MySQL query using the v ...

Reboot JavaScript once a day for optimal performance

Is it possible for the JavaScript's ?random to be based on the current date so that it only loads once a day? <script type="text/javascript" src="http://external.example.com/bookmarklet.js?random"></script> I am asking this question beca ...

Navigating through Sails.js: A comprehensive guide on executing test cases

Being a beginner in sails, node, and js, I may be missing out on some obvious steps. My environment includes sails 0.10.5 and node 0.10.33. Although the sails.js documentation covers tests in , it does not provide instructions on how to actually execute ...

Different methods to obscure solely URLs in AngularJS

Is there a way to effectively obfuscate URLs in AngularJS? Currently, I am using base 64 encoding as a method of obscuring my URLs. For example, let's say my URL is: I encode and decode it like this: aHR0cDovLzE5Mi4wLjAuMC9teS91cmwv However, when ...

The ReactJS hamburger menu fails to function after being clicked

I'm facing an issue with my responsive navbar. Whenever I click the hamburger menu, it directs me to a blank white page without any content. Can someone help me identify the problem? I am new to react and believe I might need to explore another approa ...

Implement an AJAX link on the webpage using Yii framework

I'm currently working on developing a user interface for an application, and I've encountered an issue with my code that involves adding AJAX links using a Yii helper function. echo CHtml::ajaxLink('Link', array('getajaxlinks&apos ...

Managing Events in Angular 2 and Creating Custom Event Handlers

Currently, I am in the process of developing a component library in Angular 2 for our app teams to utilize. One of the components I recently created is a modal, but I am encountering some accessibility challenges. Specifically, I want the modal to close wh ...

determining the quantity of dates

Is there a way to calculate the number of a specific day of the week occurring in a month using AngularJS? For example, how can I determine the count of Saturdays in a given month? Thank you. Here is the code snippet I have been working on: <!doctype ...

Monitor the closure of a programmatically opened tab by the user

Currently, I am in the process of developing a web application using Angular 11 that interacts with the msgraph API to facilitate file uploads to either onedrive or sharepoint, and subsequently opens the uploaded file in the Office online editor. Although ...

The TypeScript function was anticipating one argument, however it received two instead

Can you help me fix the issue with my createUser() function? Why am I unable to pass parameters in Smoke.ts? Login.ts : interface User { url: string, email: string, } class Test{ async createUser(user: User) { await Page.setUrl(user.url); aw ...

Connect ng-models with checkboxes in input field

I am facing an issue with binding ng-models using ng-repeat in an input checkbox tag. Let me share my code and elaborate further. app/main.html: <div ng-repeat="feature in features"> <input type="checkbox" ng-model="features[$index].name"> ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

What is the reason behind TypeScript requiring me to initialize a property even though I am retrieving its value from a local reference?

I am just beginning to explore Angular. This is the template for my custom component: <div class="row"> <div class="col-xs-12"> <form action=""> <div class="ro"> <d ...

Manipulating CSS styles with jQuery

Trying to update the UL image in the CSS directory using jQuery for a Twitter stream: as tweets are displayed, want to change the avatar of the account associated with each post. Using .css is straightforward, but struggling to modify the URL for the new i ...

Django: The Art of Rejuvenating Pages

Consider the following code snippet which updates the timestamp of a database model whenever it is accessed: def update_timestamp(request): entry = Entry.objects.filter(user=request.user) entry.update(timestamp=timezone.now()) return HttpRespo ...

Updating Angular Material theme variables during the build processIs this okay?

How can I easily customize the primary color of my angular 6 application to be different for development and production builds? Is there a simple solution to automatically change the primary color based on the build? ...

Angular Starter Kit

When starting with Angular.js, there are various boilerplate kits available such as angular-seed, some incorporating requirejs and more. However, many of the options I've come across seem to be outdated. As a newcomer to Angular, I'm wondering if ...

Encountering a "args" property undefined error when compiling a .ts file in Visual Studio Code IDE

I've created a tsconfig.json file with the following content: { "compilerOptions": { "target": "es5" } } In my HelloWorld.ts file, I have the following code: function SayHello() { let x = "Hello World!"; alert(x); } However ...

Using Angular to parse intricate JSON data

Need help parsing an http request in the following format: [ { "id": 1, "date": "2022-01-13T00:00:00.000+00:00", "time": "2022-01-13T21:21:21.000+00:00", "office&quo ...