使用Paste JSON as Code实现json转typeScript
- 【软件】vscode软件
创建test.json文件
{
"name": "John",
"age": 30,
"isStudent": true,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
},
"hobbies": ["reading", "painting", "playing guitar"],
"education": {
"degree": "Bachelor",
"major": "Computer Science",
"university": "ABC University",
"completed": true
},
"friends": [
{
"name": "Sarah",
"age": 28,
"address": {
"street": "456 Elm St",
"city": "Los Angeles",
"country": "USA"
},
"isCloseFriend": true
},
{
"name": "Michael",
"age": 32,
"address": {
"street": "789 Oak St",
"city": "Chicago",
"country": "USA"
},
"isCloseFriend": false
}
],
"hasPets": false
}
ctrl+shift+P打开命令面板或查看-命令面板
输入json,选择Open quicktype for JSON,即可生成QuickType.ts文件
// Generated by https://quicktype.io
//
// To change quicktype's target language, run command:
//
// "Set quicktype target language"
export interface Test {
name: string;
age: number;
isStudent: boolean;
address: Address;
hobbies: string[];
education: Education;
friends: Friend[];
hasPets: boolean;
}
export interface Address {
street: string;
city: string;
country: string;
}
export interface Education {
degree: string;
major: string;
university: string;
completed: boolean;
}
export interface Friend {
name: string;
age: number;
address: Address;
isCloseFriend: boolean;
}
复制到相对应的ts文件中编修即可,非常方便。
另外一种操作方式
ctrl+N创建一个临时文件 Untitled-1,随意输入以下代码,并ctrl+A全选复制,创建test.ts文件,ctrl+shift+p输入json,选择Paste JSON as Code。根据提示输入名称(Paste)回车。
{
"name": "John",
"age": 30,
"isStudent": true,
"address": {
"street": "123 Main St",
"city": "New York",
"country": "USA"
},
"hobbies": ["reading", "painting", "playing guitar"],
"education": {
"degree": "Bachelor",
"major": "Computer Science",
"university": "ABC University",
"completed": true
},
"friends": [
{
"name": "Sarah",
"age": 28,
"address": {
"street": "456 Elm St",
"city": "Los Angeles",
"country": "USA"
},
"isCloseFriend": true
},
{
"name": "Michael",
"age": 32,
"address": {
"street": "789 Oak St",
"city": "Chicago",
"country": "USA"
},
"isCloseFriend": false
}
],
"hasPets": false
}
// Generated by https://quicktype.io
export interface Paste {
name: string;
age: number;
isStudent: boolean;
address: Address;
hobbies: string[];
education: Education;
friends: Friend[];
hasPets: boolean;
}
export interface Address {
street: string;
city: string;
country: string;
}
export interface Education {
degree: string;
major: string;
university: string;
completed: boolean;
}
export interface Friend {
name: string;
age: number;
address: Address;
isCloseFriend: boolean;
}