What is the best method for creating a zod schema for an intricately nested object?

Here is the data I am working with:

{
  "2022-06-01": {
    "09:00am": {
      "time_table_id": 1,
      "job_id": 4,
      "start_working_time": "09:00am",
      "end_working_time": "09:00pm",
      "work_duration": "12:00:00",
      "merchant_name": "Brands Outlet @ The Starling",
      "address2": "Jalan SS 21/37, Damansara Utama",
      "job_name": "Pro hero",
      "job_application_status": "Hired"
    }
  }
}

I have created a schema to parse this data but unfortunately, I am encountering a zod error.

const apiScheme = z.object({
  Date: z.object({
    Time: z.object({
      date: z.string(),
      time_table_id: z.number().nullable(),
      job_id: z.number(),
      start_working_time: z.string(),
      end_working_time: z.string(),
      // work_duration: z.string(),
      // merchant_name: z.string(),
      // address2: z.string(),
      job_name: z.string(),
      job_application_status: z.string(),
    }),
  }),
});

// -- snip -- (React code):

const data = useMemo(() => {
  if (responseData) {
    const parseData = apiScheme.parse(responseData);
    //    error here ~~~~~~~~~~-^
    if (parseData) {
      return parseData;
    }
  }
  return null;
}, [responseData]);

Answer №1

It seems that the issue lies in using z.object instead of z.record for your specific case.

const apiSchema = z.record(
  z.string(), 
  z.record(
    z.string(),
    z.object({
      time_table_id: z.number().nullable(),
      job_id: z.number(),
      start_working_time: z.string(),
      end_working_time: z.string(),
      work_duration: z.string(),
      merchant_name: z.string(),
      address2: z.string(),
      job_name: z.string(),
      job_application_status: z.string()
    }),
  ),
);

z.object is ideal when all field names are known, while z.record is more suitable for cases where keys are not known at compile time, such as TypeScript's Record type.


Quick Note: If you're certain about fixed date and time values, consider structuring the schema like:

z.object({
  "2022-06-01": z.object({
     "09:00am": z.object({ /* ... */ }),
  },
});

However, if date and time indexes vary, the above schema may not be appropriate for your data structure (as it relies on specific date and time entries).

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

The confusion arises from the ambiguity between the name of the module and the name of

In my current scenario, I am faced with the following issue : module SomeName { class SomeName { } var namespace = SomeName; } The problem is that when referencing SomeName, it is pointing to the class instead of the module. I have a requireme ...

The disappearing act of embedded Twitter timelines in Ionic 2

My code displays the timeline initially, but it disappears when I navigate away from the view. Can anyone help me troubleshoot this issue? Upon first visit to the view, the timeline is visible, but upon returning, it disappears. Below is the code snippet ...

When working in Visual Studio Code, it is important to note that [js] types are limited to usage within

Can .js files be used in a TypeScript project in VS Code? I recently cloned a React Native project from a GitHub repository and opened it in Visual Studio Code. However, when I added a tsconfig.json file to start using TypeScript, I encountered a lengthy l ...

What is the process for transforming an arraylist of strings into an arraylist of integers and then computing the sum of the integer values?

I'm facing an issue with calculating ArrayList String from ListView values into ArrayList Integer and back to ListView in my Android application. The problem is that it only displays the last arrayList value on the textView instead of calculating them ...

Tips for handling multiple API requests in a React Flux application

I am utilizing an API that provides reports based on the "hourOfDay" parameter. http://localhost:8080/api/v1/reports/61?aggregation=hourOfDay&start=2016-02-10T00:00:00.000Z&stop=2016-02-20T10:59:59.000Z In my React App, I aim to showcase both thi ...

Storing data in the device's memory with preexisting code on the Android platform

My preference is for my application to save the necessary text file in the internal storage rather than the user's /sdcard/ to prevent potential annoyance from the creation of external files. Can anyone provide guidance on how to modify my code so tha ...

Expanding one type by utilizing it as an extension of another type

I am looking to create a custom object with predefined "base" properties, as well as additional properties. It is important for me to be able to export the type of this new object using the typeof keyword. I want to avoid having to define an interface for ...

Error in displaying custom array adapter on listview

I am trying to populate a listView with multiple objects, but I am encountering an error. This is the Android code I am using: public class ViewDosen extends AppCompatActivity { TextView tv ...

Is there a way to make ListView refresh itself automatically?

My application allows me to display received and sent SMS messages in a ListView. Below is the code snippet: public class ChatActivity extends ListActivity { private MyListAdapter adapter; ArrayList<String> item_id = new ArrayList<String>(); ...

Troubleshooting Issues with Retrieving Android Data from MySQL Database using PHP and JSON

Even though I have encountered this question multiple times on stack overflow, I have tried all the solutions provided and none of them seem to work for me. I am attempting to display data in a List View. The data is stored in JSON format and it appears t ...

Why is it necessary to re-export both * and { default } in zustand.js?

As I delved into analyzing the codebase of zustand, I stumbled upon this snippet in index.ts: export * from './vanilla' export * from './react' export { default as createStore } from './vanilla' export { default } from '. ...

Finding the accurate index of a radio button within various dynamically created radio groups on an Android platform

I am currently developing a quiz application for Android. The questions and answer options are retrieved from the database and stored in arrays, which are then assigned to table rows with two radio groups per question (each containing four options). Here&a ...

Jest has identified a single open handle that may be preventing Jest from exiting: TCPSERVERWRAP

Currently, I am conducting a basic end-to-end testing procedure which seems to be failing at the moment. The primary issue I am facing is being unable to resolve an open handle. A result of running all test suites reveals that Jest has identified one open ...

What is the process for passing information to a nested component structure with parent-child-child relationships?

I am facing an issue with three nested components (C1, C2, C3) where C2 is called within C1 and C3 is called within C2. My goal is to pass data from C1 to C3 using property binding. In the template of C1, I successfully bound a variable that I can access ...

Changes in vertical position of link icon within div based on the browser and operating system

Trying to design a straightforward 3-line mobile menu dropdown, but encountering inconsistency in appearance across different devices. The vertical positioning of the icon is varying based on the operating system and browser version: Linux -desktop Fire ...

Tips for eliminating or concealing repetitive cell text within columns

I am working with a syncfusion grid that contains repetitive data at the column level. However, I want to display only the first occurrence of the data and show a tree-like view. Please see the image below for reference: Reference Image Any suggestions on ...

Setting the initial scroll position in a ReactNative ListView after the data has been loaded

I need a solution for jumping to specific dates in an events section, with the initial scroll position set to the first future date. To achieve this, I have attempted to store the y positions of each date in the state. renderSectionHeader= (sectionData, ...

What is the most effective way to transfer data from an Activity to a pre-existing Fragment?

Recently, I've encountered a problem where I am stuck! I have an Activity (not my MainActivity) and I need to transfer some data. Despite trying various methods like using Bundle and getter, I keep encountering the error message: "Attempt to invoke vi ...

Preserve the ViewModel state during screen rotation on Android

Currently, I am delving into Android coding and came across a suggestion in the book I'm using to save the screen state: val provider = ViewModelProviders.of(this) val quizViewModel = provider.get(QuizViewModel::class.java) Log.d(TAG, &qu ...

Avoiding Unrecognized Escape Sequences when using WCF with Android

My attempts to send data to a wcf webservice are encountering issues with handling complex json. The debugger reveals that the wcf is not recognizing the incoming values and when I attempt to set the parameter, I encounter an error message about an Unrecog ...