B2BÍøÂçÈí¼þ

 ÕÒ»ØÃÜÂë
 Á¢¼´×¢²á ÉóºËÍøÕ¾ºÅ:QQ:896757558
ËÑË÷
²é¿´: 19|»Ø¸´: 0
´òÓ¡ ÉÏÒ»Ö÷Ìâ ÏÂÒ»Ö÷Ìâ

JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý

[¸´ÖÆÁ´½Ó]

1019

Ö÷Ìâ

1024

Ìû×Ó

7353

»ý·Ö

abc

Rank: 9Rank: 9Rank: 9

»ý·Ö
7353
Ìø×ªµ½Ö¸¶¨Â¥²ã
Â¥Ö÷


JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý


JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý B2BÍøÂçÈí¼þ


  1. // JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý - AIWROK IDE ¿ª·¢ (ES5 ¼æÈÝ)
  2. // չʾ´Ó»ù´¡µ½¸ß¼¶µÄËùÓÐ JSON ´¦Àí¼¼ÇÉ
  3. // ES5ϵͳ°²×¿ JavaScriptÒýÇæRhino     
  4. //🍎½»Á÷QQȺ711841924Ⱥһ£¬Æ»¹ûÄÚ²âȺ£¬528816639


  5. logWindow.show()
  6. logWindow.setAlpha(300)
  7. logWindow.setHeight(2000)
  8. logWindow.setWidth(1800)

  9. // Rhino¼æÈݵÄÈÕÆÚ¸ñʽ»¯º¯Êý
  10. function formatDateToString(date) {
  11.   if (!(date instanceof Date)) {
  12.     return date;
  13.   }
  14.   
  15.   var year = date.getFullYear();
  16.   var month = date.getMonth() + 1;
  17.   var day = date.getDate();
  18.   var hours = date.getHours();
  19.   var minutes = date.getMinutes();
  20.   var seconds = date.getSeconds();
  21.   var milliseconds = date.getMilliseconds();
  22.   
  23.   // ²¹Á㺯Êý
  24.   function pad(num) {
  25.     return num < 10 ? '0' + num : '' + num;
  26.   }
  27.   
  28.   // ²¹Á㺯Êý£¨3λºÁÃ룩
  29.   function pad3(num) {
  30.     if (num < 10) return '00' + num;
  31.     if (num < 100) return '0' + num;
  32.     return '' + num;
  33.   }
  34.   
  35.   return year + '-' + pad(month) + '-' + pad(day) + 'T' +
  36.          pad(hours) + ':' + pad(minutes) + ':' + pad(seconds) +
  37.          '.' + pad3(milliseconds) + 'Z';
  38. }

  39. // Rhino¼æÈݵÄÈÕÆÚ½âÎöº¯Êý
  40. function parseDateFromString(dateString) {
  41.   if (typeof dateString !== 'string') {
  42.     return dateString;
  43.   }
  44.   
  45.   // ¼ì²éÊÇ·ñÊDZê×¼ÈÕÆÚ¸ñʽ
  46.   var dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
  47.   if (!dateRegex.test(dateString)) {
  48.     return dateString;
  49.   }
  50.   
  51.   try {
  52.     return new Date(dateString);
  53.   } catch (err) {
  54.     printl("ÈÕÆÚ½âÎö´íÎó:", err);
  55.     print.log("ÎÞ·¨½âÎöÈÕÆÚ×Ö·û´®:", dateString);
  56.     return dateString;
  57.   }
  58. }

  59. // ==================== 1. »ù´¡Ó÷¨ ====================
  60. var user = {
  61.   name: 'AIWROK Developer',
  62.   age: 25,
  63.   skills: ['JavaScript', 'React Native', 'Node.js'],
  64.   active: true
  65. };

  66. printl("1. »ù´¡Ó÷¨");
  67. print.log("=== JSON »ù´¡Ó÷¨ ===");

  68. // »ù±¾ÐòÁл¯
  69. var jsonStr = JSON.stringify(user);
  70. printl("ÐòÁл¯½á¹û:", jsonStr);
  71. print.log("JSON.stringify(user):", jsonStr);

  72. // »ù±¾·´ÐòÁл¯
  73. var parsedUser = JSON.parse(jsonStr);
  74. printl("·´ÐòÁл¯½á¹û:", parsedUser);
  75. print.log("JSON.parse(jsonStr):", parsedUser);

  76. // ==================== 2. ÃÀ»¯Êä³ö ====================
  77. printl("");
  78. print.log("=== 2. ÃÀ»¯Êä³ö ===");

  79. var config = {
  80.   app: 'AIWROK IDE',
  81.   version: '2.1.0',
  82.   settings: {
  83.     theme: 'dark',
  84.     autoSave: true,
  85.     ai: {
  86.       enabled: true,
  87.       suggestions: true
  88.     }
  89.   }
  90. };

  91. printl("ԭʼÅäÖöÔÏó:", config);
  92. print.log("config¶ÔÏó:", config);

  93. // ÃÀ»¯Êä³ö
  94. var prettyConfig = JSON.stringify(config, null, 2);
  95. printl("ÃÀ»¯Êä³ö½á¹û:", prettyConfig);
  96. print.log("JSON.stringify(config, null, 2):", prettyConfig);

  97. // ==================== 3. ×Ô¶¨ÒåÐòÁл¯ (replacer) ====================
  98. printl("");
  99. print.log("=== 3. ×Ô¶¨ÒåÐòÁл¯ (replacer) ===");

  100. var dataWithDate = {
  101.   name: 'AIWROK ÅäÖÃ',
  102.   created: new Date('2023-06-01'),
  103.   lastModified: new Date(),
  104.   version: '1.0.0',
  105.   features: ['darkMode', 'autoSave', 'aiSuggestions']
  106. };

  107. printl("°üº¬Date¶ÔÏóµÄÊý¾Ý:", dataWithDate);
  108. print.log("ԭʼdataWithDate:", dataWithDate);

  109. // ×Ô¶¨Òå replacer º¯Êý£¬½« Date ת»»Îª×Ö·û´®
  110. var serializedData = JSON.stringify(dataWithDate, function(key, value) {
  111.   if (value instanceof Date) {
  112.     return formatDateToString(value);
  113.   }
  114.   return value;
  115. }, 2);

  116. printl("ÐòÁл¯ºó (Dateת×Ö·û´®):", serializedData);
  117. print.log("ʹÓÃreplacerºóµÄJSON:", serializedData);

  118. // ==================== 4. ×Ô¶¨Òå·´ÐòÁл¯ (reviver) ====================
  119. printl("");
  120. print.log("=== 4. ×Ô¶¨Òå·´ÐòÁл¯ (reviver) ===");

  121. // ×Ô¶¨Òå·´ÐòÁл¯º¯Êý
  122. function customReviver(key, value) {
  123.   // ¼ì²éÊÇ·ñÊÇÈÕÆÚ×Ö·û´®¸ñʽ
  124.   return parseDateFromString(value);
  125. }

  126. printl("×Ô¶¨Òåreviverº¯ÊýÒѶ¨Òå");
  127. print.log("customReviverº¯Êý: ×Ô¶¯×ª»»ÈÕÆÚ×Ö·û´®ÎªDate¶ÔÏó");

  128. var deserializedData = JSON.parse(serializedData, customReviver);
  129. printl("·´ÐòÁл¯½á¹û:", deserializedData);
  130. print.log("JSON.parse(serializedData, customReviver):", deserializedData);

  131. // ==================== 5. ÊôÐÔ¹ýÂË ====================
  132. printl("");
  133. print.log("=== 5. ÊôÐÔ¹ýÂË ===");

  134. // ¹ýÂËÃô¸ÐÐÅÏ¢µÄº¯Êý
  135. var sensitiveData = {
  136.   id: 12345,
  137.   username: 'aiwrok_dev',
  138.   email: 'dev@aiwrok.com',
  139.   password: 'secret123',
  140.   accessToken: 'abc123xyz',
  141.   profile: {
  142.     realName: 'AIWROK Developer',
  143.     phone: '13800138000',
  144.     address: '±±¾©Êг¯ÑôÇø'
  145.   }
  146. };

  147. printl("ԭʼÃô¸ÐÊý¾Ý:", sensitiveData);
  148. print.log("°üº¬ÃÜÂëµÈÃô¸ÐÐÅÏ¢µÄÊý¾Ý:", sensitiveData);

  149. var filteredJson = JSON.stringify(sensitiveData, function(key, value) {
  150.   if (key === 'password' || key === 'accessToken' || key === 'phone' || key === 'address') {
  151.     return undefined;
  152.   }
  153.   return value;
  154. }, 2);

  155. printl("¹ýÂ˺óµÄJSON:", filteredJson);
  156. print.log("ÒÆ³ýÃô¸ÐÐÅÏ¢ºóµÄ½á¹û:", filteredJson);

  157. // ==================== 6. Êý×é´¦Àí ====================
  158. printl("");
  159. print.log("=== 6. Êý×é´¦Àí ===");

  160. var projects = [
  161.   {
  162.     name: 'AIWROK IDE',
  163.     type: 'ide',
  164.     technologies: ['React', 'Electron', 'Node.js'],
  165.     status: 'active',
  166.     startDate: new Date('2023-06-01')
  167.   },
  168.   {
  169.     name: 'AIWROK Web IDE',
  170.     type: 'web',
  171.     technologies: ['React', 'Node.js', 'Monaco Editor'],
  172.     status: 'planning',
  173.     startDate: new Date('2024-01-15')
  174.   },
  175.   {
  176.     name: 'AIWROK API',
  177.     type: 'api',
  178.     technologies: ['Express', 'MongoDB', 'JWT'],
  179.     status: 'active',
  180.     startDate: new Date('2023-09-01')
  181.   }
  182. ];

  183. printl("ÏîÄ¿Êý×é:", projects);
  184. print.log("°üº¬Date¶ÔÏóµÄÊý×é:", projects);

  185. // ÐòÁл¯Êý×é
  186. var projectsJson = JSON.stringify(projects, function(key, value) {
  187.   if (key === 'startDate') {
  188.     return formatDateToString(value);
  189.   }
  190.   return value;
  191. }, 2);

  192. printl("ÐòÁл¯ºóµÄÏîÄ¿Êý×é:", projectsJson);
  193. print.log("Date¶ÔÏóת»»Îª×Ö·û´®:", projectsJson);

  194. // ·´ÐòÁл¯Êý×é
  195. var parsedProjects = JSON.parse(projectsJson, function(key, value) {
  196.   if (key === 'startDate') {
  197.     return parseDateFromString(value);
  198.   }
  199.   return value;
  200. });

  201. printl("·´ÐòÁл¯ºóµÄÏîÄ¿Êý×é:", parsedProjects);
  202. print.log("×Ö·û´®×ª»»»ØDate¶ÔÏó:", parsedProjects);

  203. // ==================== 7. ´íÎó´¦Àí ====================
  204. printl("");
  205. print.log("=== 7. ´íÎó´¦Àí ===");

  206. // °²È«½âÎöº¯Êý
  207. function safeParse(jsonString, fallback) {
  208.   fallback = fallback === undefined ? null : fallback;
  209.   try {
  210.     return JSON.parse(jsonString);
  211.   } catch (err) {
  212.     printl("JSON½âÎö´íÎó:", err);
  213.     print.log("½âÎöʧ°Ü£¬·µ»ØÄ¬ÈÏÖµ:", fallback);
  214.     return fallback;
  215.   }
  216. }

  217. // °²È«ÐòÁл¯º¯Êý - ´¦ÀíÑ­»·ÒýÓÃ
  218. function safeStringify(obj, space) {
  219.   space = space === undefined ? 0 : space;
  220.   var visited = [];
  221.   
  222.   function replacer(key, value) {
  223.     if (typeof value === 'object' && value !== null) {
  224.       // ¼ì²éÑ­»·ÒýÓÃ
  225.       if (visited.indexOf(value) !== -1) {
  226.         return '[Circular Reference]';
  227.       }
  228.       visited.push(value);
  229.     }
  230.     return value;
  231.   }
  232.   
  233.   try {
  234.     return JSON.stringify(obj, replacer, space);
  235.   } catch (err) {
  236.     printl("JSONÐòÁл¯´íÎó:", err);
  237.     print.log("ÐòÁл¯Ê§°Ü£¬·µ»Ø¿Õ¶ÔÏó");
  238.     return '{}';
  239.   }
  240. }

  241. printl("°²È«½âÎöºÍÐòÁл¯º¯ÊýÒѶ¨Òå");
  242. print.log("°üº¬´íÎó´¦ÀíµÄ¹¤¾ßº¯Êý");

  243. // ²âÊÔÓÐЧºÍÎÞЧµÄ JSON
  244. var validJson = '{"message": "Hello, AIWROK!", "status": "success"}';
  245. var invalidJson = '{"message": "Hello, AIWROK!", "status": }';

  246. printl("²âÊÔÓÐЧJSON:", validJson);
  247. print.log("validJson:", validJson);

  248. var validResult = safeParse(validJson);
  249. printl("ÓÐЧJSON½âÎö½á¹û:", validResult);
  250. print.log("safeParse(validJson):", validResult);

  251. printl("²âÊÔÎÞЧJSON:", invalidJson);
  252. print.log("invalidJson:", invalidJson);

  253. var invalidResult = safeParse(invalidJson);
  254. printl("ÎÞЧJSON½âÎö½á¹û:", invalidResult);
  255. print.log("safeParse(invalidJson):", invalidResult);

  256. // ²âÊÔÑ­»·ÒýÓÃ
  257. var circularObj = { name: 'AIWROK' };
  258. circularObj.self = circularObj;

  259. printl("²âÊÔÑ­»·ÒýÓöÔÏó:", safeStringify(circularObj, 2));
  260. print.log("circularObj°üº¬×ÔÒýÓÃ");

  261. var circularResult = safeStringify(circularObj);
  262. printl("Ñ­»·ÒýÓÃÐòÁл¯½á¹û:", circularResult);
  263. print.log("safeStringify(circularObj):", circularResult);

  264. // ==================== 8. ʵ¼ÊÓ¦ÓÃʾÀý - Óû§»á»°¹ÜÀí ====================
  265. printl("");
  266. print.log("=== 8. Óû§»á»°¹ÜÀí ===");

  267. // ȇȡˈ
  268. function UserSession(userData) {
  269.   this.user = userData;
  270.   this.loginTime = new Date();
  271.   this.lastActivity = new Date();
  272.   this.sessionId = this.generateSessionId();
  273. }

  274. UserSession.prototype.generateSessionId = function() {
  275.   return 'sess_' + Math.random().toString(36).substr(2, 9);
  276. };

  277. UserSession.prototype.updateActivity = function() {
  278.   this.lastActivity = new Date();
  279. };

  280. UserSession.prototype.getSessionInfo = function() {
  281.   return {
  282.     sessionId: this.sessionId,
  283.     user: this.user,
  284.     loginTime: formatDateToString(this.loginTime),
  285.     lastActivity: formatDateToString(this.lastActivity),
  286.     isActive: this.isSessionActive()
  287.   };
  288. };

  289. UserSession.prototype.isSessionActive = function() {
  290.   var now = new Date();
  291.   var timeDiff = now - this.lastActivity;
  292.   return timeDiff < 30 * 60 * 1000; // 30·ÖÖÓÎ޻ÊÓΪ¹ýÆÚ
  293. };

  294. UserSession.prototype.serialize = function() {
  295.   var self = this;
  296.   return JSON.stringify(this, function(key, value) {
  297.     if (key === 'loginTime' || key === 'lastActivity') {
  298.       return formatDateToString(value);
  299.     }
  300.     // ±ÜÃâÐòÁл¯Ô­ÐÍÁ´Éϵķ½·¨
  301.     if (typeof value === 'function') {
  302.       return undefined;
  303.     }
  304.     return value;
  305.   });
  306. };

  307. UserSession.prototype.deserialize = function(jsonString) {
  308.   try {
  309.     var data = JSON.parse(jsonString);
  310.     this.user = data.user;
  311.     this.loginTime = parseDateFromString(data.loginTime);
  312.     this.lastActivity = parseDateFromString(data.lastActivity);
  313.     this.sessionId = data.sessionId;
  314.     return true;
  315.   } catch (err) {
  316.     printl("»á»°·´ÐòÁл¯´íÎó:", err);
  317.     print.log("»Ö¸´»á»°Ê§°Ü:", err);
  318.     return false;
  319.   }
  320. };

  321. printl("UserSessionÀàÒѶ¨Òå");
  322. print.log("°üº¬ÐòÁл¯¡¢·´ÐòÁл¯µÈ·½·¨");

  323. // ´´½¨Óû§»á»°
  324. var userData = {
  325.   id: 1001,
  326.   username: 'aiwrok_dev',
  327.   permissions: ['read', 'write', 'admin']
  328. };

  329. var session = new UserSession(userData);
  330. printl("´´½¨Óû§»á»°:", session.getSessionInfo());
  331. print.log("session¶ÔÏó:", session.getSessionInfo());

  332. // ±£´æ»á»°µ½±¾µØ´æ´¢
  333. var sessionJson = session.serialize();
  334. printl("ÐòÁл¯ºóµÄ»á»°Êý¾Ý:", sessionJson);
  335. print.log("session.serialize():", sessionJson);

  336. var mockStorage = {
  337.   data: {},
  338.   setItem: function(key, value) {
  339.     this.data[key] = value;
  340.   },
  341.   getItem: function(key) {
  342.     return this.data[key];
  343.   }
  344. };

  345. mockStorage.setItem('aiwrok_user_session', sessionJson);
  346. printl("»á»°Êý¾ÝÒѱ£´æµ½´æ´¢");
  347. print.log("±£´æµ½localStorageÄ£Äâ");

  348. // ´Ó±¾µØ´æ´¢»Ö¸´»á»°
  349. var restoredSession = new UserSession({});
  350. var sessionData = mockStorage.getItem('aiwrok_user_session');
  351. if (restoredSession.deserialize(sessionData)) {
  352.   printl("»á»°»Ö¸´³É¹¦:", restoredSession.getSessionInfo());
  353.   print.log("»á»°»Ö¸´³É¹¦:", restoredSession.getSessionInfo());
  354. } else {
  355.   printl("»á»°»Ö¸´Ê§°Ü");
  356.   print.log("»Ö¸´Ê§°Ü£¬¿ÉÄÜÊÇÊý¾ÝËð»µ");
  357. }

  358. // ==================== 9. ÏîÄ¿ÅäÖùÜÀí ====================
  359. printl("");
  360. print.log("=== 9. ÏîÄ¿ÅäÖùÜÀí ===");

  361. // ÏîÄ¿ÅäÖÃÀà
  362. function ProjectConfig() {
  363.   this.configs = {};
  364. }

  365. ProjectConfig.prototype.save = function(name, config) {
  366.   this.configs[name] = config;
  367. };

  368. ProjectConfig.prototype.get = function(name) {
  369.   return this.configs[name] || null;
  370. };

  371. ProjectConfig.prototype.getAll = function() {
  372.   return this.configs;
  373. };

  374. printl("ProjectConfigÀàÒѶ¨Òå");
  375. print.log("ÅäÖùÜÀíÀà: save, get, getAll·½·¨");

  376. var projectConfig = {
  377.   name: 'AIWROK IDE Project',
  378.   version: '2.1.0',
  379.   created: new Date('2023-06-01'),
  380.   lastModified: new Date(),
  381.   features: {
  382.     darkMode: true,
  383.     autoSave: true,
  384.     intelliSense: true,
  385.     codeFormatting: true
  386.   },
  387.   dependencies: {
  388.     core: ['react', 'react-native'],
  389.     dev: ['jest', 'eslint', 'prettier'],
  390.     ui: ['react-native-vector-icons', 'react-native-gesture-handler']
  391.   }
  392. };

  393. printl("ÏîÄ¿ÅäÖöÔÏó:", projectConfig);
  394. print.log("°üº¬Date¶ÔÏóºÍǶÌ×¶ÔÏó");

  395. // ±£´æÏîÄ¿ÅäÖõ½±¾µØ´æ´¢
  396. function saveProjectConfig(config) {
  397.   var serialized = JSON.stringify(config, function(key, value) {
  398.     if (value instanceof Date) {
  399.       return formatDateToString(value);
  400.     }
  401.     return value;
  402.   }, 2);
  403.   
  404.   // Ä£Äâ localStorage ±£´æ
  405.   mockStorage.setItem('aiwrok_project_config', serialized);
  406.   return serialized;
  407. }

  408. // ¼ÓÔØÏîÄ¿ÅäÖÃ
  409. function loadProjectConfig() {
  410.   var stored = mockStorage.getItem('aiwrok_project_config');
  411.   if (!stored) return null;
  412.   
  413.   try {
  414.     return JSON.parse(stored, function(key, value) {
  415.       // ×Ô¶¯×ª»»ÈÕÆÚ×Ö·û´®Îª Date ¶ÔÏó
  416.       if (key === 'created' || key === 'lastModified') {
  417.         return parseDateFromString(value);
  418.       }
  419.       return value;
  420.     });
  421.   } catch (err) {
  422.     printl("¼ÓÔØÅäÖôíÎó:", err);
  423.     print.log("ÅäÖýâÎöʧ°Ü:", err);
  424.     return null;
  425.   }
  426. }

  427. printl("ÅäÖñ£´æºÍ¼ÓÔØº¯ÊýÒѶ¨Òå");
  428. print.log("×Ô¶¯´¦ÀíDate¶ÔÏóת»»");

  429. var savedConfig = saveProjectConfig(projectConfig);
  430. printl("±£´æÅäÖýá¹û:", savedConfig);
  431. print.log("saveProjectConfig·µ»Ø:", savedConfig);

  432. var loadedConfig = loadProjectConfig();
  433. printl("¼ÓÔØÅäÖýá¹û:", loadedConfig);
  434. print.log("loadProjectConfig·µ»Ø:", loadedConfig);

  435. if (loadedConfig && loadedConfig.created instanceof Date) {
  436.   printl("Date¶ÔÏó»Ö¸´³É¹¦");
  437.   print.log("loadedConfig.createdÊÇDate¶ÔÏó:", loadedConfig.created);
  438. } else {
  439.   printl("Date¶ÔÏó»Ö¸´Ê§°Ü");
  440.   print.log("loadedConfig.created²»ÊÇDate¶ÔÏó");
  441. }

  442. // ==================== 10. ´úÂëÆ¬¶Î¹ÜÀí ====================
  443. printl("");
  444. print.log("=== 10. ´úÂëÆ¬¶Î¹ÜÀí ===");

  445. // ´úÂëÆ¬¶Î´æ´¢
  446. function CodeSnippetManager() {
  447.   this.snippets = [];
  448. }

  449. CodeSnippetManager.prototype.addSnippet = function(name, language, code, description) {
  450.   description = description === undefined ? '' : description;
  451.   var snippet = {
  452.     id: Date.now(),
  453.     name: name,
  454.     language: language,
  455.     code: code,
  456.     description: description,
  457.     createdAt: new Date(),
  458.     tags: this.extractTags(code)
  459.   };
  460.   
  461.   this.snippets.push(snippet);
  462.   return snippet;
  463. };

  464. CodeSnippetManager.prototype.extractTags = function(code) {
  465.   var commonPatterns = {
  466.     'React': /import.*from\s+['"]react['"]/,
  467.     'React Native': /from\s+['"]react-native['"]/,
  468.     'API': /fetch\(|axios\./,
  469.     'Async': /async\s+|await\s+/,
  470.     'ES6': /const\s+|let\s+|=>/
  471.   };
  472.   
  473.   var tags = [];
  474.   for (var keyword in commonPatterns) {
  475.     if (commonPatterns.hasOwnProperty(keyword) && commonPatterns[keyword].test(code)) {
  476.       tags.push(keyword.toLowerCase());
  477.     }
  478.   }
  479.   return tags;
  480. };

  481. CodeSnippetManager.prototype.searchSnippets = function(keyword) {
  482.   return this.snippets.filter(function(snippet) {
  483.     return snippet.name.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
  484.            snippet.code.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
  485.            snippet.description.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
  486.            snippet.tags.some(function(tag) { return tag.indexOf(keyword.toLowerCase()) !== -1; });
  487.   });
  488. };

  489. CodeSnippetManager.prototype.exportSnippets = function() {
  490.   return JSON.stringify(this.snippets, function(key, value) {
  491.     if (key === 'createdAt') {
  492.       return formatDateToString(value);
  493.     }
  494.     return value;
  495.   }, 2);
  496. };

  497. CodeSnippetManager.prototype.importSnippets = function(jsonString) {
  498.   try {
  499.     var snippets = JSON.parse(jsonString, function(key, value) {
  500.       if (key === 'createdAt') {
  501.         return parseDateFromString(value);
  502.       }
  503.       return value;
  504.     });
  505.    
  506.     this.snippets = snippets;
  507.     return true;
  508.   } catch (err) {
  509.     printl("µ¼Èë´úÂëÆ¬¶Î´íÎó:", err);
  510.     print.log("µ¼Èëʧ°Ü:", err);
  511.     return false;
  512.   }
  513. };

  514. CodeSnippetManager.prototype.saveToStorage = function() {
  515.   var data = {
  516.     snippets: this.snippets,
  517.     exportedAt: new Date()
  518.   };
  519.   var serialized = JSON.stringify(data, function(key, value) {
  520.     if (value instanceof Date) {
  521.       return formatDateToString(value);
  522.     }
  523.     return value;
  524.   }, 2);
  525.   mockStorage.setItem('aiwrok_code_snippets', serialized);
  526. };

  527. CodeSnippetManager.prototype.loadFromStorage = function() {
  528.   var stored = mockStorage.getItem('aiwrok_code_snippets');
  529.   if (!stored) return false;
  530.   
  531.   try {
  532.     var data = JSON.parse(stored, function(key, value) {
  533.       if (key === 'exportedAt' || key === 'createdAt') {
  534.         return parseDateFromString(value);
  535.       }
  536.       return value;
  537.     });
  538.    
  539.     this.snippets = data.snippets;
  540.     return true;
  541.   } catch (err) {
  542.     printl("¼ÓÔØ´úÂëÆ¬¶Î´íÎó:", err);
  543.     print.log("¼ÓÔØÊ§°Ü:", err);
  544.     return false;
  545.   }
  546. };

  547. printl("CodeSnippetManagerÀàÒѶ¨Òå");
  548. print.log("°üº¬Ìí¼Ó¡¢ËÑË÷¡¢µ¼Èëµ¼³öµÈ¹¦ÄÜ");

  549. // ´´½¨´úÂëÆ¬¶Î¹ÜÀíÆ÷
  550. var snippetManager = new CodeSnippetManager();
  551. printl("´´½¨´úÂëÆ¬¶Î¹ÜÀíÆ÷");
  552. print.log("snippetManagerʵÀýÒÑ´´½¨");

  553. // Ìí¼ÓʾÀý´úÂëÆ¬¶Î
  554. var snippet1 = snippetManager.addSnippet(
  555.   'React Hook',
  556.   'javascript',
  557.   'import React from \'react\';\\n\\nvar MyComponent = function() {\\n  var data = null;\\n  var setData = function() {};\\n  \\n  // Ä£Äâ useState\\n  // Ä£Äâ useEffect\\n  // Ä£Äâ fetch Êý¾Ý\\n  function fetchData() {\\n    // Ä£Äâ API µ÷ÓÃ\\n    var result = { title: \'Example Title\' };\\n    setData(result);\\n  }\\n  \\n  return React.createElement(\'div\', null, data ? data.title : \'Loading...\');\\n};\\n\\nmodule.exports = MyComponent;',
  558.   'React ×é¼þÄ£°å (ES5 °æ±¾)'
  559. );

  560. printl("Ìí¼Ó´úÂëÆ¬¶Î1:", snippet1.name);
  561. print.log("snippet1:", snippet1.name);

  562. var snippet2 = snippetManager.addSnippet(
  563.   'API ¿Í»§¶Ë',
  564.   'javascript',
  565.   'function ApiClient(baseURL) {\\n  this.baseURL = baseURL;\\n}\\n\\nApiClient.prototype.request = function(endpoint, options) {\\n  options = options === undefined ? {} : options;\\n  var url = this.baseURL + endpoint;\\n  var config = {\\n    headers: {\\n      \'Content-Type\': \'application/json\'\\n    }\\n  };\\n  \\n  // ºÏ²¢Ñ¡Ïî\\n  for (var key in options) {\\n    if (options.hasOwnProperty(key)) {\\n      config[key] = options[key];\\n    }\\n  }\\n  \\n  return {\\n    success: true,\\n    data: { message: \'Example API response\' },\\n    config: config\\n  };\\n};\\n\\n// ʹÓÃʾÀý\\nvar api = new ApiClient(\'https://api.example.com\');\\nvar response = api.request(\'/users\');',
  566.   'ͨÓà API ¿Í»§¶ËÀà (ES5 °æ±¾)'
  567. );

  568. printl("Ìí¼Ó´úÂëÆ¬¶Î2:", snippet2.name);
  569. print.log("snippet2:", snippet2.name);

  570. // ±£´æµ½±¾µØ´æ´¢
  571. snippetManager.saveToStorage();
  572. printl("´úÂëÆ¬¶ÎÒѱ£´æµ½´æ´¢");
  573. print.log("±£´æµ½localStorageÄ£Äâ");

  574. // ËÑË÷¹¦ÄܲâÊÔ
  575. var searchResults = snippetManager.searchSnippets('react');
  576. printl("ËÑË÷'react'µÄ½á¹û:", searchResults.length, "¸öƬ¶Î");
  577. print.log("ËÑË÷½á¹û:", searchResults.length);

  578. // µ¼³ö´úÂëÆ¬¶Î
  579. var exportedSnippets = snippetManager.exportSnippets();
  580. printl("µ¼³öµÄ´úÂëÆ¬¶ÎJSON:", exportedSnippets);
  581. print.log("exportSnippets():", exportedSnippets);

  582. // ==================== 11. ÐÔÄܶԱÈÑÝʾ ====================
  583. printl("");
  584. print.log("=== 11. ÐÔÄܶԱÈÑÝʾ ===");

  585. // ´´½¨²âÊÔÊý¾Ý
  586. var testData = {
  587.   largeArray: [],
  588.   summary: {
  589.     total: 1000,
  590.     active: 500,
  591.     inactive: 500
  592.   }
  593. };

  594. printl("´´½¨²âÊÔÊý¾Ý¶ÔÏó");
  595. print.log("°üº¬1000¸öÏîÄ¿µÄÊý×é");

  596. for (var k = 0; k < 1000; k++) {
  597.   testData.largeArray.push({
  598.     id: k,
  599.     name: 'ÏîÄ¿ ' + k,
  600.     status: k % 2 === 0 ? 'active' : 'inactive',
  601.     metadata: {
  602.       created: new Date(),
  603.       tags: ['tag1', 'tag2', 'tag3'],
  604.       config: { enabled: true, priority: k }
  605.     }
  606.   });
  607. }

  608. printl("²âÊÔÊý¾Ý´´½¨Íê³É£¬¹²", testData.largeArray.length, "¸öÏîÄ¿");
  609. print.log("testData°üº¬", testData.largeArray.length, "¸öÏîÄ¿");

  610. // ²âÊÔÐòÁл¯ÐÔÄÜ
  611. var startTime = Date.now();
  612. var serializedLarge = JSON.stringify(testData);
  613. var serializeTime = Date.now() - startTime;

  614. printl("ÐòÁл¯ºÄʱ:", serializeTime, "ºÁÃë");
  615. print.log("JSON.stringifyºÄʱ:", serializeTime, "ms");

  616. var startTime2 = Date.now();
  617. var deserializedLarge = JSON.parse(serializedLarge);
  618. var deserializeTime = Date.now() - startTime2;

  619. printl("·´ÐòÁл¯ºÄʱ:", deserializeTime, "ºÁÃë");
  620. print.log("JSON.parseºÄʱ:", deserializeTime, "ms");

  621. printl("×ܺÄʱ:", serializeTime + deserializeTime, "ºÁÃë");
  622. print.log("ÍêÕûJSON²Ù×÷×ܺÄʱ:", serializeTime + deserializeTime, "ms");

  623. // ==================== 12. JSON ¹¤¾ßº¯Êý ====================
  624. printl("");
  625. print.log("=== 12. JSON ¹¤¾ßº¯Êý ===");

  626. function JsonUtils() {}

  627. JsonUtils.isValidJSON = function(str) {
  628.   try {
  629.     JSON.parse(str);
  630.     return true;
  631.   } catch (e) {
  632.     return false;
  633.   }
  634. };

  635. JsonUtils.safeStringify = function(obj, fallback, replacer) {
  636.   fallback = fallback === undefined ? '{}' : fallback;
  637.   replacer = replacer === undefined ? null : replacer;
  638.   try {
  639.     return JSON.stringify(obj, replacer, 2);
  640.   } catch (err) {
  641.     printl("safeStringify´íÎó:", err);
  642.     print.log("°²È«ÐòÁл¯Ê§°Ü:", err);
  643.     return fallback;
  644.   }
  645. };

  646. JsonUtils.safeParse = function(str, fallback, reviver) {
  647.   fallback = fallback === undefined ? null : fallback;
  648.   reviver = reviver === undefined ? null : reviver;
  649.   try {
  650.     return JSON.parse(str, reviver);
  651.   } catch (err) {
  652.     printl("safeParse´íÎó:", err);
  653.     print.log("°²È«½âÎöʧ°Ü:", err);
  654.     return fallback;
  655.   }
  656. };

  657. JsonUtils.validateObjectStructure = function(obj, requiredFields) {
  658.   var missing = [];
  659.   var invalid = [];
  660.   
  661.   for (var m = 0; m < requiredFields.length; m++) {
  662.     var field = requiredFields[m];
  663.     if (!(field in obj)) {
  664.       missing.push(field);
  665.     } else if (obj[field] === null || obj[field] === undefined || obj[field] === '') {
  666.       invalid.push(field);
  667.     }
  668.   }
  669.   
  670.   return {
  671.     isValid: missing.length === 0 && invalid.length === 0,
  672.     missing: missing,
  673.     invalid: invalid
  674.   };
  675. };

  676. printl("JsonUtils¹¤¾ßÀàÒѶ¨Òå");
  677. print.log("°üº¬isValidJSON, safeStringify, safeParse, validateObjectStructure");

  678. // ²âÊÔ JSON ¹¤¾ß
  679. var testValidJSON = '{"name": "AIWROK", "version": "1.0.0"}';
  680. var testInvalidJSON = '{"name": "AIWROK", "version": }';

  681. printl("²âÊÔÓÐЧJSON:", testValidJSON);
  682. print.log("testValidJSON:", testValidJSON);

  683. var validResult = JsonUtils.isValidJSON(testValidJSON);
  684. printl("ÓÐЧJSONÑéÖ¤½á¹û:", validResult);
  685. print.log("JsonUtils.isValidJSON(testValidJSON):", validResult);

  686. printl("²âÊÔÎÞЧJSON:", testInvalidJSON);
  687. print.log("testInvalidJSON:", testInvalidJSON);

  688. var invalidResult = JsonUtils.isValidJSON(testInvalidJSON);
  689. printl("ÎÞЧJSONÑéÖ¤½á¹û:", invalidResult);
  690. print.log("JsonUtils.isValidJSON(testInvalidJSON):", invalidResult);

  691. var safeParsed = JsonUtils.safeParse(testInvalidJSON, { error: true });
  692. printl("°²È«½âÎö½á¹û:", safeParsed);
  693. print.log("JsonUtils.safeParse(testInvalidJSON):", safeParsed);

  694. var testObj = { name: 'AIWROK', version: '1.0.0' };
  695. var required = ['name', 'version', 'author'];
  696. var validation = JsonUtils.validateObjectStructure(testObj, required);

  697. printl("¶ÔÏó½á¹¹ÑéÖ¤:", validation);
  698. print.log("JsonUtils.validateObjectStructure:", validation);

  699. printl("");
  700. print.log("=== JSON´¦ÀíÍêÕûʾÀýÍê³É ===");
  701. printl("&#128161; ÕâЩ¼¼ÇÉÔÚʵ¼ÊÏîÄ¿¿ª·¢Öзdz£ÓÐÓã¡");
  702. print.log("ËùÓÐJSON²Ù×÷ʾÀýÒÑÍê³É£¡");
¸´ÖÆ´úÂë


»Ø¸´

ʹÓõÀ¾ß ¾Ù±¨

±¾°æ»ý·Ö¹æÔò

¹Ø±Õ

QQ|»ÓªÏúÈí¼þ×ÛºÏÌÖÂÛ|»ÓªÏúÈí¼þÓÐÎʱشð|»ÓªÏúÈí¼þ½Ì³Ì×¨Çø|»ÓªÏúÈí¼þPOST½Å±¾·ÖÏí|»ÓªÏúÈí¼þÆÕͨ½Å±¾·ÖÏí|»ÓªÏúÈí¼þÈí¼þ×ÊѶ|»ÓªÏúÈí¼þ¾«Æ·Èí¼þ|»ÓªÏúÈí¼þ¸üй«¸æ|ÓªÏúÈí¼þ|B2BÈí¼þ|B2BÍøÂçÈí¼þ ( ¾©ICP±¸09078825ºÅ )±¾ÍøÕ¾¿ª·¢µÄÓªÏúÈí¼þÊÇÒ»¿îеÄÍøÂçÓªÏúÈí¼þ£¬Õâ¿îÓªÏú¿ÉÒÔÈ¥ÍøÕ¾Èí¼þ£¬²©¿ÍÈí¼þ£¬B2BÈí¼þ£¬·ÖÀàÐÅÏ¢Íø·¢Ìù£¬¿ÉÒÔÇÀɳ·¢£¬¿ÉÒÔµ½°Ù¶ÈÎÄ¿âÉÏ´«WORDÎĵµ£¬¿ÉÒÔµ½Ò»Ð©ÊÇÏà²áÍøÕ¾×Ô¶¯ÉÏ´«Í¼Æ¬£¬Õâ¸ö×Ô¶¯·¢ÌûÈí¼þ×Ô´øÔÆÖ©Ö룬¼Ó¿ìÊÕ¼£¬ÓÐ6ÖÖ¶Ô½Ó´òÂë½Ó¿Ú£¬·½±ã£¬Ð§Âʸߣ¬Ëٶȿ죬¶øÇÒ¶ÔÍ϶¯µÄÑéÖ¤ÂëÈ«ÍøµÚÒ»¼Ò¶À¼ÒÖ§³Ö£¬È«²¿Ô­´´¼¼Êõ£¬¶À¼ÒÑз¢£¬Õý°æÔ­´´´ø°æÈ¨Èí¼þ¡£Ñ¡ÔñÍòÄÜÓªÏúÈí¼þ£¬¾ÍÑ¡ÔñÁËÒ»ÖÖ׬ǮµÄЧÂÊ£¬´ÓûÓб»³¬Ô½¹ý£¬Ò»Ö±ÔÚŬÁ¦Ñз¢Ð¼¼Êõ¡£·Å·ÉÃÎÏ룬½â·ÅË«ÊÖ£¬À´µã´´Ò⣬³É¾ÍÄãµÄÃÎÏ룬¾ÍÔÚÍòÄÜÓªÏúÈí¼þ¿ªÊ¼

map2

GMT+8, 2026-1-9 05:01 , Processed in 0.201189 second(s), 36 queries .

¿ìËٻظ´ ·µ»Ø¶¥²¿ ·µ»ØÁбí