简体   繁体   中英

Is there some way to convert a json file to an object model in Deno?

Issue: When i try to read a file (student.json) and store it in a variable of type Student[] it says "Type 'unknown' is not assignable to type 'Student[]'." This is a typescript file.

import { Student } from "../Models/studentModel.ts";
import { readJson, writeJson } from "https://deno.land/std/fs/mod.ts";

const f = await readJson("../public/student.json");
const students:Student[] = f;

export const get_all_students = (ctx: Context) => {
  return ctx.json(students,200);
};

Expectation: I am trying to return the json from the file to the server. Solutions tried: I have tried Json.stringify(). It still gives me the same error.

readJson method return promise type of unknown. The unknown type is only assignable to the any type and the unknown type itself.

If you want to force the compiler to trust you that a value of type unknown is of a given type, you can use a type assertion like this:

 const f = await readJson("./public/student.json");
 const students:Student[] = f as Student[];

To solve the above error just use a type assertion :

const students = f as Student[];

I'm not familiar with deno, but pretty sure you could just write the file to response stream or serve it with appropriate headers. Not sure if that makes sense for your scenario.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM