Guide to parsing unprocessed JSON into a specified format including a Date field

I need help figuring out how to import a raw JSON data file and automatically convert my date string to a date object within my type.

In my type definition:

export type Client = {
    id: number;
    first_name: string;
    last_name: string;
    dob: Date;
}

The contents of my client.json file are:

[{"id":1,"first_name":"Alasdair","last_name":"Kingman","dob":"1969-07-11"},
{"id":2,"first_name":"Ursulina","last_name":"Skellion","dob":"1986-01-08"}]

My client.ts file includes the following:

import {Client} from "./model";
import clients_raw from "../mock-data/clients/clients.json" with {type: "json"}


const clients: Client[] = clients_raw as Client[];

Using the as operator is causing an error:

TS2352: Conversion of type
....
Types of property dob are incompatible.
Type string is not comparable to type Date

Is there a way to import the dob field directly as a Date object? Or should I manually handle the conversion? Although, this manual approach seems inefficient as it will iterate over the entire array whenever the module is loaded.

const clients: Client[] = clients_raw.map((client) : Client => {
    return {...client, dob: new Date(client.dob) }
});

I'm hoping there's a more efficient solution available?

Answer №1

It is indeed impossible to achieve. One must manually create the Date object as casting will not be effective. Keep in mind that TypeScript transpiles to JavaScript, losing all type information. It is best to stick with your second method.

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

Why JSON.parse is unable to determine if the argument is already in JSON format

When using JSON.parse, it typically parses a stringified JSON. However, if a variable is already in the form of JSON and you attempt to parse it with JSON.parse, an error is thrown: > a [] > a = JSON.parse(a) SyntaxError: Unexpected end of input ...

Error in Swift: JSON Decoder Type Mismatch

Encountering an issue while trying to decode JSON data, resulting in the following error: typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 1972", intValue: 1972), CodingKeys(stringValue: "s ...

Enforce numerical input in input field by implementing a custom validator in Angular 2

After extensive research, I was unable to find a satisfactory solution to my query. Despite browsing through various Stack Overflow questions, none of them had an accepted answer. The desired functionality for the custom validator is to restrict input to ...

The property 'label' is not found in the 'string' type in Typescript

Below is the code snippet I am using: interface State { resourceGroup: QuickPickItem | string; } setEvent(state.resourceGroup?.label).catch(err => console.error(err)); When executing this code, I encountered the following error messa ...

Release date approaching, but not as anticipated

Utilizing Java servlet to construct a portion of HTML and sending it with a JsonPrimitive for display in a dialog box. Here is the code snippet: ja = new JsonPrimitive( "<a href='#' onclick='return showDueDateUpdateDialogue(" + invoice. ...

The 'ascii' codec is unable to encode the character because its ordinal value is outside the range of 0-127

Currently, I am utilizing selenium and beautifulsoup to scrape various webpages. Within this process, I am iterating through multiple links, extracting information, and storing it in a JSON format: for event in events: case = {'Artist': item ...

Make a front-end server GET request and retrieve a JSON object

NEW INFORMATION: I have successfully resolved the issue and answered this question. To achieve what I intended to do, follow these steps: var app = angular.module('myApp', []); app.factory('server', ['$http', function($htt ...

Aeson is unable to locate a key that I know should be here

Recently, I came across a tricky situation where I needed to parse a JSON blob structured like this: "{\"order_book\":{\"asks\":[[\"0.06777\",\"0.00006744\"],[\" ...

How long does it take to delete and recreate a cloudfront distribution using AWS CDK?

I am currently undergoing the process of migrating from the AWS CDK CloudfrontWebDistribution construct to the Distribution Construct. According to the documentation, the CDK will delete and recreate the distribution. I am curious about the total duration ...

Issue with applying value changes in Timeout on Angular Material components

I'm currently experimenting with Angular, and I seem to be struggling with displaying a fake progress bar using the "angular/material/progress-bar" component. (https://material.angular.io/components/progress-bar/) In my "app.component.html", I have m ...

Using the useContext hook in a TypeScript class component: a step-by-step guide

I am working with a TypeScript class component and have successfully created a context that can be accessed globally. I am interested in learning how to implement this context in a .ts class component and if it is possible to use it in a pure TypeScript ...

What are alternative methods for reading JSON files in PHP that do not involve file_get_contents()?

Recently, I developed a basic PHP script that fetches data from a local JSON file and uses it to respond to various queries directed at the page. In my implementation, I adopted the usage of file_get_contents() for reading the file. However, as the number ...

Too many characters are included in the PHP JSON response

I am trying to retrieve a JSON object from PHP using the following code: $resultFromDB = PerformTransaction($requestToDB); if($resultFromDB['status'] == '0'){ $myReturn = array('status' => '0' ...

Deciphering enigmatic JSON data

public abstract class A { public string Foo{ get; set; } } public class B : A { public string Marco{ get; set; } } public class C : A { public string Las{ get; set; } } public class D : A { public string Las{ get; set; } } public class ...

Storing an array in a file using Swift

In the process of developing an application, I have successfully implemented functionality to: Check for an internet connection; Receive a JSON file from the server and store the data in a file if the server is reachable; Read from the file if the connec ...

Can you explain how to invoke a class with express().use function?

Currently, I am delving into learning Node JS with TypeScript but have hit a roadblock with a particular issue. In my app.ts file, I have initialized the express and attempted to call the router class inside the app.use() method, only to encounter an error ...

Detecting changes in Angular when the @Input() value remains the same

I have created an Angular Custom scroll directive that utilizes an @Input() to pass an HTML element as a parameter, allowing the scrollbar to move to that specific element. However, I've encountered an issue where if I pass the same HTML Element mult ...

Different ways to update the AutoComplete Style attribute

MuiInput-formControl { margin-top: 16px; Is there a way to reset the marginTop property to zero? I attempted the following method, but it was not successful. MuiFormControlLabel: { marginTop: 0, }, <Autocomplete disabl ...

Transforming a Pandas DataFrame into a specialized nested JSON structure

I need to convert a Pandas Dataframe into nested json format. I attempted using the to_json function, but it only converts the entire dataframe as key-value pairs. I am unsure of how to achieve a nested json structure like this. Any assistance would be gre ...

Is there a way to customize the JSON-wrapped key for a class without being able to annotate the class with @JsonTypeInfo?

I have the following code snippet: import org.codehaus.jackson.map.*; public class MyPojo { int id; public int getId() { return this.id; } public void setId(int id) { this.id = id; } public static void main(String[] args) throws ...