utils.ts 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. type JsonValue = string | number | boolean | JsonObject | JsonArray;
  2. interface JsonObject {
  3. [key: string]: JsonValue
  4. }
  5. type JsonArray = Array<JsonValue>;
  6. export function generateJsonString(count: number, nested: number): string {
  7. function generateRandomString(): string {
  8. const length = Math.floor(Math.random() * 20) + 5;
  9. const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  10. return Array.from({ length }, () => characters[Math.floor(Math.random() * characters.length)]).join('');
  11. }
  12. function generateRandomObject(depth: number): JsonObject {
  13. const obj: JsonObject = {};
  14. const prefixes = ['id', 'name', 'value', 'data', 'item'];
  15. // 始终生成5个键值对,每种类型各一个
  16. obj[`${prefixes[0]}`] = Math.floor(Math.random() * 1000); // number
  17. obj[`${prefixes[1]}`] = generateRandomString(); // string
  18. obj[`${prefixes[2]}`] = Math.random() > 0.5; // boolean
  19. if (depth < nested) {
  20. obj[`${prefixes[3]}`] = generateJsonArray(depth + 1); // array
  21. obj[`${prefixes[4]}`] = generateRandomObject(depth + 1); // object
  22. } else {
  23. // 在达到最大深度时,用基本类型替代
  24. obj[`${prefixes[3]}`] = Math.floor(Math.random() * 1000); // 用number替代array
  25. obj[`${prefixes[4]}`] = generateRandomString(); // 用string替代object
  26. }
  27. return obj;
  28. }
  29. function generateJsonArray(depth: number): JsonArray {
  30. const array: JsonArray = [];
  31. // 始终生成5个元素,每种类型各一个
  32. array.push(Math.floor(Math.random() * 1000)); // number
  33. array.push(generateRandomString()); // string
  34. array.push(Math.random() > 0.5); // boolean
  35. if (depth < nested) {
  36. array.push(generateJsonArray(depth + 1)); // array
  37. array.push(generateRandomObject(depth + 1)); // object
  38. } else {
  39. // 在达到最大深度时,用基本类型替代
  40. array.push(Math.floor(Math.random() * 1000)); // 用number替代array
  41. array.push(generateRandomString()); // 用string替代object
  42. }
  43. return array;
  44. }
  45. function generateJson(): JsonObject[] {
  46. const json: JsonObject[] = [];
  47. for (let i = 0; i < count; i++) {
  48. json.push(generateRandomObject(1));
  49. }
  50. return json;
  51. }
  52. const json = generateJson();
  53. return JSON.stringify(json, null, 4); // 格式化输出
  54. }