Having issues with JSON.stringify not properly handling every property within an object in Typescript

While using JSON.stringify in Typescript, I encountered an issue where not all properties of the outermost object were being stringified. Here is the code snippet that showcases the problem:

class Criterion {
    '@CLASS' = 'xyz.abc.Criterion'
    operator: string;
    operand: string[];
    field: string;
    constructor(field:string,operator:string,operand: string[]) {
      this.field = field;
      this.operator = operator;
      this.operand = operand;
    }
}

class Filter {
    '@CLASS': 'xyz.ada.Filter';
    criteria: Criterion[];
    constructor(criteria:Criterion[]) {
        this.criteria=criteria;
    }
}

var criterion = new Criterion("a","b",["c"]);
var a = new Filter([criterion]);
JSON.stringify(a);
console.log(JSON.stringify(a));

Output:

{"criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}

Expected:

{"@CLASS":"xyz.ada.Filter","criteria":[{"@CLASS":"xyz.abc.Criterion","field":"a","operator":"b","operand":["c"]}]}

The issue lies in the fact that the @CLASS property of the Filter class object is not being properly stringified.

code link

Answer №1

You have a mistake in your class filter. Update the two dots to:

'@CLASS'= 'xyz.ada.Filter';

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

Can the WebSocket interface be substituted with WebSocket itself?

I'm currently in the process of setting up a WebSocket.Server using ws, Express 4, NodeJS, and TypeScript by following a guide. However, I've encountered an issue with the provided code not working as expected from the tutorial found at . In ord ...

How to Fetch Byte Image with Ajax and Display it on the Client Side in ASP.Net MVC

After converting an image to bytes, I am facing the challenge of displaying the byteImage in a browser. I have two sets of data, one being the Image ID and the other being the Image_name, which are displayed in a table. However, I am unable to display the ...

Converting a file array to JSON format using Python socket programming

How can I print the file names I've created to the console without my loop running infinitely? from socket import * import os import math serverPort = 12000 # Create a UDP socket serverSocket = socket(AF_INET, SOCK_DGRAM) content_name = 'py&apos ...

My webpage is experiencing issues with function calls not functioning as expected

I have created a select menu that is integrated with the Google Font API. To demonstrate how it works, I have set up a working version on JSBIN which you can view here. However, when I tried to replicate the code in an HTML page, I encountered some issues ...

Error: The XML file is missing the root element

My REST Api returns json as HttpResponseMessage. Everything works fine when I run it on localhost on my computer and I receive the json result. However, when I host it on the IIS server on another system, I encountered the following error: { "Messa ...

What is the importance of setting up an HTTP server?

Can anyone explain why, in nodeJs programming with javascript, it is necessary to establish a server using the http module, even though one could simply utilize the fs module for reading, writing, and updating data stored in a json file? ...

Vue and TypeScript: The elusive 'exports' remains unidentified

Since switching my App.vue to utilize typescript, I am facing a compiler error: [tsl] ERROR in \src\main.ts(2,23) TS2304: Unable to locate the name 'exports'. If I have vue-serve recompile after making changes, I encounter t ...

Exploring the versatility of multi-dimensional arrays using JSON encoding

Here are the scripts I've written in Python and PHP to multiply two matrices in a Python file. $arr2=array(array(array(1,2),array(3,5)) ,array(array(4,6)array(2,7))) echo json_encode($arr2); $rtu= shell_exec("C:/Python27/python 1234.py ".json_encode( ...

display additional data in JSON format from standard object

Below is a snippet of code that checks whether values in a table are NULL or not, and then echoes a message to the view informing the user if the value already exists. The code takes a multiselect input and queries the MySQL database for the selected IDs. ...

Enabling a mat-slide-toggle to be automatically set to true using formControl

Is there a way to ensure that the mat-slide-toggle remains true under certain conditions? I am looking for a functionality similar to forcedTrue="someCondition". <mat-slide-toggle formControlName="compression" class="m ...

What is causing VSCode's TypeScript checker to overlook these specific imported types?

Encountering a frustrating dilemma within VS Code while working on my Vite/Vue frontend project. It appears that certain types imported from my Node backend are unable to be located. Within my frontend: https://i.stack.imgur.com/NSTRM.png The presence o ...

What is the proper way to define an array of objects in TypeScript?

In search of a way to define a function that accepts an array of unspecified object types, known as "anonymous types." I want to enforce strict typing with TypeScript. The objects in the array all have properties like name, price, and description. bagTotal ...

Tips for type guarding in TypeScript when using instanceof, which only works with classes

Looking for a way to type guard with TypeScript types without using instanceof: type Letter = 'A' | 'B'; const isLetter = (c: any): c is Letter => c instanceof Letter; // Error: 'Letter' only refers to a type, but is being ...

How can you typically verify the type of an object variable in TypeScript?

How can I verify if the obj variable contains all the properties defined in the Person interface? interface Person { name: string; age: number; } const jsonObj = `{ name: "John Doe", age: 30, }`; const obj: Person = JSON.parse(jsonObj); ...

Converting Antdesign's Datepicker to Typescript

I'm having trouble figuring out how to properly annotate the dateObj parameter in the handleDateChange function that I've created. App.tsx import { useState } from 'react'; import logo from './logo.svg'; ...

Angular 7 and its scrolling div

Currently, I am working on implementing a straightforward drag and drop feature. When dragging an item, my goal is to scroll the containing div by a specified amount in either direction. To achieve this, I am utilizing Angular Material's CDK drag an ...

What is the reason for the typescript check failing?

When attempting to check for the existence of an attribute using if statement, I encountered an error. Can anyone explain why this happened? I would appreciate any insights on this issue. ...

Issue: The use of destructuring props is required by eslint, and I'm currently working with a combination of react and types

I typically work with React in JavaScript, and I recently encountered an error message stating "Must use destructuring props at line 14" while trying to define a button for use in a form. Here is the code snippet in question: import React from 'react& ...

How to display a variety of JSON data in different templates with unique variables using angularjs

I am curious about the best approach to handling a response that contains various types of objects presented like this: [ {"nodeClass":"Entity", "text":"foo","entityfield":"booz"}, {"nodeClass":"User","username":"bar","userfield":"baz"} ] Each type of ob ...

Python initially encounters a HTTPError 400 Client Error when attempting to retrieve information, yet upon manually visiting the URL, the retrieval process

Every time I execute this code in iPython (Python 2.7): from requests import get _get = get('http://stats.nba.com/stats/playergamelog', params={'PlayerID': 203083, 'Season':'2015-16', 'SeasonType':'Re ...