基于JS怎么将JSON数据转换为TypeScript类型声明的工具

前端开发   发布日期:2024年11月08日   浏览次数:459

这篇文章主要介绍“基于JS怎么将JSON数据转换为TypeScript类型声明的工具”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“基于JS怎么将JSON数据转换为TypeScript类型声明的工具”文章能帮助大家解决问题。

    一、实现的功能

    • 将 JSON 数据转换为 TypeScript 类型定义。

    • 支持嵌套的复杂类型,如数组和对象。

    • 支持自定义类型名称和命名空间。

    • 支持将转换后的 TypeScript 类型定义保存为文件。

    二、工具使用方法

    安装工具:

    npm install -g my-json-to-ts

    运行工具:

    my-json-to-ts input.json output.ts

    其中

    1. input.json
    是要转换的 JSON 文件路径,
    1. output.ts
    是转换后的 TypeScript 文件路径。

    --name 类型名称 # 指定转换后的类型名称,默认为 JsonType
    --namespace 命名空间 # 指定转换后的命名空间,默认为无
    --no-file # 不将转换后的 TypeScript 类型定义保存为文件

    三、实现思路

    • 读取输入的 JSON 文件,解析成 JSON 对象。

    • 遍历 JSON 对象,根据不同的类型生成对应的 TypeScript 类型定义字符串。

    • 如果指定了类型名称和命名空间,则在生成的 TypeScript 类型定义字符串前面添加对应的声明。

    • 如果指定了保存文件,则将生成的 TypeScript 类型定义字符串写入文件。

    四、使用示例

    以下是将JSON 数据和转换后的 TypeScript 类型定义示例:

    简单的JSON 数据

    1. {
    2. "name": "John",
    3. "age": 30,
    4. "address": {
    5. "city": "New York",
    6. "state": "NY"
    7. },
    8. "hobbies": [
    9. "reading",
    10. "traveling"
    11. ]
    12. }

    输出对应简单的类型定义

    1. interface JsonType {
    2. name: string;
    3. age: number;
    4. address: {
    5. city: string;
    6. state: string;
    7. };
    8. hobbies: string[];
    9. }

    复杂的JSON 数据

    1. {
    2. "name": "John",
    3. "age": 30,
    4. "address": {
    5. "city": "New York",
    6. "state": "NY",
    7. "postalCode": 10001
    8. },
    9. "friends": [
    10. {
    11. "name": "Jane",
    12. "age": 28,
    13. "address": {
    14. "city": "Los Angeles",
    15. "state": "CA"
    16. }
    17. },
    18. {
    19. "name": "Bob",
    20. "age": 35,
    21. "address": {
    22. "city": "Chicago",
    23. "state": "IL"
    24. }
    25. }
    26. ],
    27. "hobbies": [
    28. "reading",
    29. "traveling",
    30. {
    31. "name": "swimming",
    32. "location": "pool"
    33. }
    34. ]
    35. }

    输出对应复杂类型定义

    1. interface JsonType {
    2. name: string;
    3. age: number;
    4. address: {
    5. city: string;
    6. state: string;
    7. postalCode: number;
    8. };
    9. friends: {
    10. name: string;
    11. age: number;
    12. address: {
    13. city: string;
    14. state: string;
    15. };
    16. }[];
    17. hobbies: (string | {
    18. name: string;
    19. location: string;
    20. })[];
    21. }

    五、具体实现代码

    首先引入两个 Node.js 模块:

    1. fs-extra
    1. commander
    1. fs-extra
    是一个简化了 Node.js 文件系统模块的封装,而
    1. commander
    是一个命令行工具的库,可以方便地解析命令行参数。

    接下来定义一个函数

    1. jsonToTs
    ,用于将 JSON 数据转换为 TypeScript 类型定义字符串。该函数采用递归的方式遍历 JSON 数据,生成对应的 TypeScript 类型定义。如果 JSON 数据是数组,则递归处理其中的每个元素;如果是对象,则递归处理其中的每个属性。最终,该函数返回一个 TypeScript 类型定义字符串。

    然后定义了两个异步函数,

    1. readJson
    1. writeTs
    ,分别用于读取 JSON 文件和将 TypeScript 类型定义字符串写入文件。

    最后定义一个名为

    1. jsonToTsFile
    的函数,该函数接收命令行参数并将其传递给
    1. jsonToTs
    函数,然后将生成的 TypeScript 类型定义字符串保存到文件中。如果命令行参数中指定了不保存文件,则该函数将直接将 TypeScript 类型定义字符串输出到控制台。
    1. const fs = require('fs-extra');
    2. const commander = require('commander');
    3. /**
    4. * 将 JSON 数据转换为 TypeScript 类型定义
    5. * @param {Object} object - 要转换的 JSON 对象
    6. * @param {string} [name=JsonType] - 转换后的类型名称
    7. * @param {string} [namespace] - 转换后的命名空间
    8. * @returns {string} - 转换后的 TypeScript 类型定义字符串
    9. */
    10. function jsonToTs(object, name = 'JsonType', namespace) {
    11. const getType = value => {
    12. let typeRes = ``;
    13. if (Array.isArray(value)) {
    14. value.forEach(item => {
    15. let subType = getType(item);
    16. if (typeRes.split('|').indexOf(subType) < 0) {
    17. typeRes += subType
    18. typeRes += "|"
    19. }
    20. })
    21. typeRes = typeRes.substring(0, typeRes.length - 1)
    22. return `(${typeRes})[]`;
    23. }
    24. if (typeof value === 'object' && value !== null) {
    25. const props = Object.entries(value)
    26. .map(([key, val]) => `${key}: ${getType(val)}`)
    27. .join('; ');
    28. return `{ ${props} }`;
    29. }
    30. return typeof value;
    31. };
    32. const type = getType(object);
    33. const declaration = `interface ${name} ${type}`;
    34. return namespace ? `namespace ${namespace} {
    35. ${declaration}
    36. }` : declaration;
    37. }
    38. /**
    39. * 读取文件并解析成 JSON 对象
    40. * @param {string} path - 文件路径
    41. * @returns {Promise<Object>} - JSON 对象
    42. */
    43. async function readJson(path) {
    44. const content = await fs.readFile(path, 'utf8');
    45. return JSON.parse(content);
    46. }
    47. /**
    48. * 将 TypeScript 类型定义字符串写入文件
    49. * @param {string} content - TypeScript 类型定义字符串
    50. * @param {string} path - 文件路径
    51. * @returns {Promise<void>}
    52. */
    53. async function writeTs(content, path) {
    54. await fs.writeFile(path, content, 'utf8');
    55. }
    56. /**
    57. * 将 JSON 数据转换为 TypeScript 类型定义
    58. * @param {string} inputPath - 输入 JSON 文件路径
    59. * @param {string} outputPath - 输出 TypeScript 文件路径
    60. * @param {string} [options.name=JsonType] - 转换后的类型名称
    61. * @param {string} [options.namespace] - 转换后的命名空间
    62. * @param {boolean} [options.noFile] - 不将 TypeScript 类型定义保存为文件
    63. * @returns {Promise<void>}
    64. */
    65. async function jsonToTsFile(inputPath, outputPath, options) {
    66. const { name, namespace, noFile } = options
    67. try {
    68. const object = await readJson(inputPath);
    69. const type = jsonToTs(object, name, namespace);
    70. if (noFile) {
    71. console.log(type);
    72. } else {
    73. await writeTs(type, outputPath);
    74. console.log(`Type definition saved to ${outputPath}`);
    75. }
    76. } catch (err) {
    77. console.error(err.message);
    78. }
    79. }
    80. const program = new commander.Command();
    81. program
    82. .arguments('<input> <output>')
    83. .option('--no-file', 'do not save to file')
    84. .option('-s, --namespace <namespace>', 'type namespace')
    85. .option('-n, --name <name>', 'type name', 'JsonType')
    86. .action(jsonToTsFile);
    87. program.parse(process.argv);

    以上就是基于JS怎么将JSON数据转换为TypeScript类型声明的工具的详细内容,更多关于基于JS怎么将JSON数据转换为TypeScript类型声明的工具的资料请关注九品源码其它相关文章!