Title: How to get Angular JSON serializer to ignore null values?
Tags: json;angular;angular-httpclient
Question: I have an object that I send using HttpClient who may have some null properties. I wonder if there are any build-in solution(s) in Angular that ensure that null properties are not serialized.
Lets take this model for instance:
export class Dummy {
public constructor(
public readonly foo: string,
public readonly bar: string
) { }
And this service:
import { HttpClient } from '@angular/common/http';
export class DummyService {
public constructor(private readonly httpClient: HttpClient) { }
public dummyMethod(dummyObject: Dummy): Observable<any&gt; {
return this.httpClient.Post('https://api.dummy/v1/dummies', dummyObject)
If dummyObject === new Dummy("FooValue", null) then I expect this JSON to be serialized: { "foo": "FooValue" }
Comment: could you use `undefined` instead of `null`? `JSON.stringify`, which is user under the hood by the `HttpClient`, will ignore properties that are undefined

Here is the accepted answer: In JSON, values must be one of the following data types:
a string
a number
an object (JSON object)
an array
a boolean
So it can't ignore null. But we can't see undefined here, so you can use it instead of null and serialised object will omit it.


{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 1, 'CommentCount': 1, 'ContentLicense': 'CC BY-SA 4.0', 'CreationDate': '2019:00:06/04/19', 'FavoriteCount': 1.0, 'PostTypeId': 1, 'Tags': '<json><angular><angular-httpclient>', 'Title': 'How to get Angular JSON serializer to ignore null values?', 'ViewCount': 3058, 'id': 56446296, 'user_AboutMe': '<p>I love mechas as I love monsters: the bigger they are, the more I love them.</p>\n', 'user_AccountId': 8185037.0, 'user_DisplayName': 'Thomas Perez', 'user_Reputation': 129.0, 'user_Views': 19.0, 'user_id': 6161096.0}}