简体   繁体   English

有没有办法在 Deno 中将 json 文件转换为 object model 文件?

[英]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[]'."问题:当我尝试读取文件 (student.json) 并将其存储在 Student [] 类型的变量中时,它显示“类型‘未知’不可分配给类型‘学生 []’。” This is a typescript file.这是一个 typescript 文件。

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.期望:我正在尝试将 json 从文件返回到服务器。 Solutions tried: I have tried Json.stringify().尝试的解决方案:我尝试过 Json.stringify()。 It still gives me the same error.它仍然给我同样的错误。

readJson method return promise type of unknown. readJson 方法返回 promise 类型未知。 The unknown type is only assignable to the any type and the unknown type itself.未知类型只能分配给 any 类型和未知类型本身。

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.我不熟悉 deno,但很确定您可以编写文件以响应 stream 或使用适当的标头提供它。 Not sure if that makes sense for your scenario.不确定这对您的场景是否有意义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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