json - 将 JSON 转换为 TS 对象
问题描述
我有一些这样的json;
例子.json
{
"id": 1,
"name": "John Doe",
"age": 23,
"country": "US",
"language": "en",
"created_at": 1534774253,
"updated_at": 1534774269
}
我有一个这样的 user.ts 界面;
用户.ts
interface user {
id: number;
name: string;
age: number;
country: string
}
那么,如何将此 json 转换为从此接口实现的对象?我试过const userObj: user = JSON.parse(exampleJson);
了,但 userObj 具有 json 中的所有属性。我想生成一个只有 user.ts 属性的用户对象。例如 => JSON.stringify(userObj);
,输出为{"id":1,"name":"John Doe","age":23,"country":"US"}
。
有人知道方法吗?
解决方案
Typescript 接口是一种帮助为您的代码编辑器提供智能感知(提示)和强类型化 JSON 的方法。它没有帮助您处理清除不需要的其他属性的功能。因此,当你这样做时const userObj: user = JSON.parse(exampleJson)
,你仍然会得到像created_at
.
我认为您可以实现所需的一种方法可能是编写一个类。
class User {
id: number;
name: string;
age: number;
country: string;
constructor(jsonString: any) {
const userObj = JSON.parse(jsonString);
// this part could be shorten with for loop
this.id = userObj.id;
this.name = userObj.name;
this.age = userObj.age;
this.country = userObj.country;
}
}
稍后您可以使用它:
const userObj = new User(exampleJson);
推荐阅读
- python - 将列表元组的列表写入 CSV
- mysql - Docker 在 mysql 容器上导入 sql 脚本
- sql - 更新状态并立即调度
- spring-boot - 在 Spring Boot 应用程序中使用 Soap Web 服务时出错
- python - 你如何在 Python 中使用 pdflatex?
- makefile - 当 -e 用作前缀时,MAKE 中的 addprefix 无法正常工作
- apache - Apache 2.4 白名单一个网址
- sql - 我如何表示一个由 3 个其他实体组成的实体?
- slack-api - 我怎样才能让它看起来像一个机器人正在输入松弛?
- blazor - Blazor、Debug.WriteLine 未输出到 Google Chrome 控制台