繁体   English   中英

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

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

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

期望:我正在尝试将 json 从文件返回到服务器。 尝试的解决方案:我尝试过 Json.stringify()。 它仍然给我同样的错误。

readJson 方法返回 promise 类型未知。 未知类型只能分配给 any 类型和未知类型本身。

如果你想强制编译器相信你未知类型的值是给定类型的,你可以使用这样的类型断言:

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

要解决上述错误,只需使用类型断言

const students = f as Student[];

我不熟悉 deno,但很确定您可以编写文件以响应 stream 或使用适当的标头提供它。 不确定这对您的场景是否有意义。

暂无
暂无

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

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