Using Typescript to Convert JSON Data into Object Instances

My challenge involves a Json object structure that looks something like this:

{
  "key" : "false",
  "key2" : "1.00",
  "key3" : "value"
}

I am seeking to convert this in Typescript to achieve the following transformation:

{
  "key" : false,
  "key2" : 1.00,
  "key3" : "value"
}

Despite attempts using methods such as JSON.parse(JSON.stringify(json)), JSON.parse(json) and Object.assign(object, json), I have not been able to make any progress.

Answer №1

The main issue lies in the fact that `JSON.parse` does not automatically convert strings representing valid boolean and float values to their respective types. Instead, it keeps them as strings. To address this problem in cases like the one you presented, manual conversion of the strings is necessary:

let source = { "key": "false", "key2": "1.00", "key3": "value" };
let destination = {
    key: source.key !== "true",
    key2: parseFloat(source.key2),
    key3: source.key3
};

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 can you add or remove an item from an array of objects in Angular/RXJS using Observables?

Purpose: The goal is to append a new object to an existing Observable array of objects and ensure that this change is visible on the DOM as the final step. NewObject.ts: export class NewObject { name: string; title: string; } Here's the example ...

Tips for successfully passing the dynamic state and setState to a function in typescript

I'm encountering an issue with passing dynamic state and setState into a function using Typescript. Despite trying to use Generics, I am facing complaints from Typescript. Here is the code snippet: const handleSelectTag = (tag: { color: string; labe ...

Attempting to iterate through a JSON object containing nested objects and arrays of objects

For hours, I've been struggling to navigate through this json file with no success. When I log the data, it shows that Response is an Object, data is also an object, and saleItemCategories is an array containing four objects. The first object in the ...

Iterating through a nested JSON object using Java

I am currently working with a JSON object that contains nested child objects. My goal is to loop through the entire structure and extract all account_id's and id's when they appear together in the same child object, storing them in a single array ...

Working with CURL involving a specified port and extra parameters within the URL, as well as JSON data

Recently, I stumbled upon a URL with an interesting format: http://www.domain.com:10001/api/Data.cgi?Scope=System This URL contains a JSON dump that I need to parse. However, as someone who has previously only used get_file_contents, I am struggling due t ...

Eliminate all citation markers in the final compiled result

Currently, I am consolidating all my .ts files into a single file using the following command: tsc -out app.js app.ts --removeComments This is based on the instructions provided in the npm documentation. However, even after compilation, all reference tag ...

Verify whether the JSON response includes an object

I am attempting to determine if a JSON response contains objects, and execute a specific action if it does. The issue I'm facing is that even when the response includes objects, the break statement does not trigger. Below is the code snippet I am wo ...

What is the method for inserting a specific index into an interface array in TypeScript?

In my angular(typescript) application, I have an interface defined as follows: export interface PartnerCnic{ id: string; shipperRegCnicFront: File; shipperRegCnicBack: File; } Within my component, I have initialized an empty array for this interface li ...

Is there a way to retrieve the type of a generic class in JavaScript?

class Alpha { static construct<T extends typeof Alpha>(this: T): InstanceType<T> { const v = new Alpha(); return v as InstanceType<T>; } } class Beta extends Alpha {} const x = Alpha.construct(); // generates Alpha const y = ...

The specified argument, 'void', cannot be assigned to a parameter that expects 'SetStateAction | undefined'

Currently, I am engaged in a TypeScript project where I am fetching data from an endpoint. The issue arises when I attempt to assign the retrieved data to my state variable nft using the useState hook's setNft function. An error is being thrown specif ...

The method hasOwnProperty does not function as intended

Upon receiving a JSON object from the server ({error:true}), I attempted to verify if the key "error" exists. Surprisingly, the function hasOwnProperty returned false. Here is the snippet of code that led to this unexpected result: $http({ header ...

Retrieve the index values from an array within a BigQuery data JSON

After importing data from Firestore to BigQuery, I noticed that the format of my data aligns closely with this: data = [ { id: "item1", status: { options: [ { title: "Approved", color: "#00ff00" }, ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...

Decoding JSON in AWS Lambda using Go programming language

In the process of developing an application, we have implemented an AWS Lambda function that processes a post request, performs some operations on it, and then continues. This Lambda function is triggered by an API Gateway Request, with the body of the req ...

Extract data from a JSON-encoded array using JavaScript

I sent a JSON encoded array to JavaScript. Now I want to access that array to retrieve the different elements. When I print it out using console.log(), I see this array: array(1) { [16]=> array(2) { [3488]=> array(1) { [0]=> ...

Issue with Typescript and React: Property not found on type 'IntrinsicAttributes'

While working on my app using Meteor, React, and Typescript, I encountered a transpiling error: The property 'gameId' is not recognized in the type 'IntrinsicAttributes & {} & { children?: ReactNode; } In my project, I have a com ...

Angular 2 routing for dynamic population in a grid system

My website is compiling correctly, however, in the Sprint dropdown menu where I have set up routing... <a *ngFor = "let item of sprint;" routerLink = "/Summary" routerLinkActive = "active"> <button *ngIf = "item.Name" mat-menu-item sty ...

"Tree panel items in ExtJS 4 are displaying correctly in Firefox, but are mysteriously missing from

While working on my Tree Panel project, I encountered an issue with the display of items in different browsers. The items show up correctly in Firefox but appear empty in Chromium. How is this possible? Here's the JSON data sent to the server: {"tex ...

Using createStackNavigator along with createBottomTabNavigator in React Navigation version 5

I have recently started working with react native and I am using the latest version of react-navigation (v.5) in my react-native application. However, I encountered errors when trying to use createStackNavigator and createBottomTabNavigator together within ...

Understanding the mechanisms of Promise functionality within Typescript can be challenging, particularly when encountering error messages such as "type void is not

Recently, I've delved into the world of Typescript. Despite my efforts to stay true to the typing system, I've encountered a challenge that forces me to resort to using the any type: The issue arises with a function that returns a promise: sav ...