|
|
JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý
- // JSON.stringify ºÍ JSON.parse ÍêÕûʾÀý - AIWROK IDE ¿ª·¢ (ES5 ¼æÈÝ)
- // չʾ´Ó»ù´¡µ½¸ß¼¶µÄËùÓÐ JSON ´¦Àí¼¼ÇÉ
- // ES5ϵͳ°²×¿ JavaScriptÒýÇæRhino
- //🍎½»Á÷QQȺ711841924Ⱥһ£¬Æ»¹ûÄÚ²âȺ£¬528816639
- logWindow.show()
- logWindow.setAlpha(300)
- logWindow.setHeight(2000)
- logWindow.setWidth(1800)
- // Rhino¼æÈݵÄÈÕÆÚ¸ñʽ»¯º¯Êý
- function formatDateToString(date) {
- if (!(date instanceof Date)) {
- return date;
- }
-
- var year = date.getFullYear();
- var month = date.getMonth() + 1;
- var day = date.getDate();
- var hours = date.getHours();
- var minutes = date.getMinutes();
- var seconds = date.getSeconds();
- var milliseconds = date.getMilliseconds();
-
- // ²¹Á㺯Êý
- function pad(num) {
- return num < 10 ? '0' + num : '' + num;
- }
-
- // ²¹Á㺯Êý£¨3λºÁÃ룩
- function pad3(num) {
- if (num < 10) return '00' + num;
- if (num < 100) return '0' + num;
- return '' + num;
- }
-
- return year + '-' + pad(month) + '-' + pad(day) + 'T' +
- pad(hours) + ':' + pad(minutes) + ':' + pad(seconds) +
- '.' + pad3(milliseconds) + 'Z';
- }
- // Rhino¼æÈݵÄÈÕÆÚ½âÎöº¯Êý
- function parseDateFromString(dateString) {
- if (typeof dateString !== 'string') {
- return dateString;
- }
-
- // ¼ì²éÊÇ·ñÊDZê×¼ÈÕÆÚ¸ñʽ
- var dateRegex = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{3})?Z$/;
- if (!dateRegex.test(dateString)) {
- return dateString;
- }
-
- try {
- return new Date(dateString);
- } catch (err) {
- printl("ÈÕÆÚ½âÎö´íÎó:", err);
- print.log("ÎÞ·¨½âÎöÈÕÆÚ×Ö·û´®:", dateString);
- return dateString;
- }
- }
- // ==================== 1. »ù´¡Ó÷¨ ====================
- var user = {
- name: 'AIWROK Developer',
- age: 25,
- skills: ['JavaScript', 'React Native', 'Node.js'],
- active: true
- };
- printl("1. »ù´¡Ó÷¨");
- print.log("=== JSON »ù´¡Ó÷¨ ===");
- // »ù±¾ÐòÁл¯
- var jsonStr = JSON.stringify(user);
- printl("ÐòÁл¯½á¹û:", jsonStr);
- print.log("JSON.stringify(user):", jsonStr);
- // »ù±¾·´ÐòÁл¯
- var parsedUser = JSON.parse(jsonStr);
- printl("·´ÐòÁл¯½á¹û:", parsedUser);
- print.log("JSON.parse(jsonStr):", parsedUser);
- // ==================== 2. ÃÀ»¯Êä³ö ====================
- printl("");
- print.log("=== 2. ÃÀ»¯Êä³ö ===");
- var config = {
- app: 'AIWROK IDE',
- version: '2.1.0',
- settings: {
- theme: 'dark',
- autoSave: true,
- ai: {
- enabled: true,
- suggestions: true
- }
- }
- };
- printl("ÔʼÅäÖöÔÏó:", config);
- print.log("config¶ÔÏó:", config);
- // ÃÀ»¯Êä³ö
- var prettyConfig = JSON.stringify(config, null, 2);
- printl("ÃÀ»¯Êä³ö½á¹û:", prettyConfig);
- print.log("JSON.stringify(config, null, 2):", prettyConfig);
- // ==================== 3. ×Ô¶¨ÒåÐòÁл¯ (replacer) ====================
- printl("");
- print.log("=== 3. ×Ô¶¨ÒåÐòÁл¯ (replacer) ===");
- var dataWithDate = {
- name: 'AIWROK ÅäÖÃ',
- created: new Date('2023-06-01'),
- lastModified: new Date(),
- version: '1.0.0',
- features: ['darkMode', 'autoSave', 'aiSuggestions']
- };
- printl("°üº¬Date¶ÔÏóµÄÊý¾Ý:", dataWithDate);
- print.log("ÔʼdataWithDate:", dataWithDate);
- // ×Ô¶¨Òå replacer º¯Êý£¬½« Date ת»»Îª×Ö·û´®
- var serializedData = JSON.stringify(dataWithDate, function(key, value) {
- if (value instanceof Date) {
- return formatDateToString(value);
- }
- return value;
- }, 2);
- printl("ÐòÁл¯ºó (Dateת×Ö·û´®):", serializedData);
- print.log("ʹÓÃreplacerºóµÄJSON:", serializedData);
- // ==================== 4. ×Ô¶¨Òå·´ÐòÁл¯ (reviver) ====================
- printl("");
- print.log("=== 4. ×Ô¶¨Òå·´ÐòÁл¯ (reviver) ===");
- // ×Ô¶¨Òå·´ÐòÁл¯º¯Êý
- function customReviver(key, value) {
- // ¼ì²éÊÇ·ñÊÇÈÕÆÚ×Ö·û´®¸ñʽ
- return parseDateFromString(value);
- }
- printl("×Ô¶¨Òåreviverº¯ÊýÒѶ¨Òå");
- print.log("customReviverº¯Êý: ×Ô¶¯×ª»»ÈÕÆÚ×Ö·û´®ÎªDate¶ÔÏó");
- var deserializedData = JSON.parse(serializedData, customReviver);
- printl("·´ÐòÁл¯½á¹û:", deserializedData);
- print.log("JSON.parse(serializedData, customReviver):", deserializedData);
- // ==================== 5. ÊôÐÔ¹ýÂË ====================
- printl("");
- print.log("=== 5. ÊôÐÔ¹ýÂË ===");
- // ¹ýÂËÃô¸ÐÐÅÏ¢µÄº¯Êý
- var sensitiveData = {
- id: 12345,
- username: 'aiwrok_dev',
- email: 'dev@aiwrok.com',
- password: 'secret123',
- accessToken: 'abc123xyz',
- profile: {
- realName: 'AIWROK Developer',
- phone: '13800138000',
- address: '±±¾©Êг¯ÑôÇø'
- }
- };
- printl("ÔʼÃô¸ÐÊý¾Ý:", sensitiveData);
- print.log("°üº¬ÃÜÂëµÈÃô¸ÐÐÅÏ¢µÄÊý¾Ý:", sensitiveData);
- var filteredJson = JSON.stringify(sensitiveData, function(key, value) {
- if (key === 'password' || key === 'accessToken' || key === 'phone' || key === 'address') {
- return undefined;
- }
- return value;
- }, 2);
- printl("¹ýÂ˺óµÄJSON:", filteredJson);
- print.log("ÒÆ³ýÃô¸ÐÐÅÏ¢ºóµÄ½á¹û:", filteredJson);
- // ==================== 6. Êý×é´¦Àí ====================
- printl("");
- print.log("=== 6. Êý×é´¦Àí ===");
- var projects = [
- {
- name: 'AIWROK IDE',
- type: 'ide',
- technologies: ['React', 'Electron', 'Node.js'],
- status: 'active',
- startDate: new Date('2023-06-01')
- },
- {
- name: 'AIWROK Web IDE',
- type: 'web',
- technologies: ['React', 'Node.js', 'Monaco Editor'],
- status: 'planning',
- startDate: new Date('2024-01-15')
- },
- {
- name: 'AIWROK API',
- type: 'api',
- technologies: ['Express', 'MongoDB', 'JWT'],
- status: 'active',
- startDate: new Date('2023-09-01')
- }
- ];
- printl("ÏîÄ¿Êý×é:", projects);
- print.log("°üº¬Date¶ÔÏóµÄÊý×é:", projects);
- // ÐòÁл¯Êý×é
- var projectsJson = JSON.stringify(projects, function(key, value) {
- if (key === 'startDate') {
- return formatDateToString(value);
- }
- return value;
- }, 2);
- printl("ÐòÁл¯ºóµÄÏîÄ¿Êý×é:", projectsJson);
- print.log("Date¶ÔÏóת»»Îª×Ö·û´®:", projectsJson);
- // ·´ÐòÁл¯Êý×é
- var parsedProjects = JSON.parse(projectsJson, function(key, value) {
- if (key === 'startDate') {
- return parseDateFromString(value);
- }
- return value;
- });
- printl("·´ÐòÁл¯ºóµÄÏîÄ¿Êý×é:", parsedProjects);
- print.log("×Ö·û´®×ª»»»ØDate¶ÔÏó:", parsedProjects);
- // ==================== 7. ´íÎó´¦Àí ====================
- printl("");
- print.log("=== 7. ´íÎó´¦Àí ===");
- // °²È«½âÎöº¯Êý
- function safeParse(jsonString, fallback) {
- fallback = fallback === undefined ? null : fallback;
- try {
- return JSON.parse(jsonString);
- } catch (err) {
- printl("JSON½âÎö´íÎó:", err);
- print.log("½âÎöʧ°Ü£¬·µ»ØÄ¬ÈÏÖµ:", fallback);
- return fallback;
- }
- }
- // °²È«ÐòÁл¯º¯Êý - ´¦ÀíÑ»·ÒýÓÃ
- function safeStringify(obj, space) {
- space = space === undefined ? 0 : space;
- var visited = [];
-
- function replacer(key, value) {
- if (typeof value === 'object' && value !== null) {
- // ¼ì²éÑ»·ÒýÓÃ
- if (visited.indexOf(value) !== -1) {
- return '[Circular Reference]';
- }
- visited.push(value);
- }
- return value;
- }
-
- try {
- return JSON.stringify(obj, replacer, space);
- } catch (err) {
- printl("JSONÐòÁл¯´íÎó:", err);
- print.log("ÐòÁл¯Ê§°Ü£¬·µ»Ø¿Õ¶ÔÏó");
- return '{}';
- }
- }
- printl("°²È«½âÎöºÍÐòÁл¯º¯ÊýÒѶ¨Òå");
- print.log("°üº¬´íÎó´¦ÀíµÄ¹¤¾ßº¯Êý");
- // ²âÊÔÓÐЧºÍÎÞЧµÄ JSON
- var validJson = '{"message": "Hello, AIWROK!", "status": "success"}';
- var invalidJson = '{"message": "Hello, AIWROK!", "status": }';
- printl("²âÊÔÓÐЧJSON:", validJson);
- print.log("validJson:", validJson);
- var validResult = safeParse(validJson);
- printl("ÓÐЧJSON½âÎö½á¹û:", validResult);
- print.log("safeParse(validJson):", validResult);
- printl("²âÊÔÎÞЧJSON:", invalidJson);
- print.log("invalidJson:", invalidJson);
- var invalidResult = safeParse(invalidJson);
- printl("ÎÞЧJSON½âÎö½á¹û:", invalidResult);
- print.log("safeParse(invalidJson):", invalidResult);
- // ²âÊÔÑ»·ÒýÓÃ
- var circularObj = { name: 'AIWROK' };
- circularObj.self = circularObj;
- printl("²âÊÔÑ»·ÒýÓöÔÏó:", safeStringify(circularObj, 2));
- print.log("circularObj°üº¬×ÔÒýÓÃ");
- var circularResult = safeStringify(circularObj);
- printl("Ñ»·ÒýÓÃÐòÁл¯½á¹û:", circularResult);
- print.log("safeStringify(circularObj):", circularResult);
- // ==================== 8. ʵ¼ÊÓ¦ÓÃʾÀý - Óû§»á»°¹ÜÀí ====================
- printl("");
- print.log("=== 8. Óû§»á»°¹ÜÀí ===");
- // ȇȡˈ
- function UserSession(userData) {
- this.user = userData;
- this.loginTime = new Date();
- this.lastActivity = new Date();
- this.sessionId = this.generateSessionId();
- }
- UserSession.prototype.generateSessionId = function() {
- return 'sess_' + Math.random().toString(36).substr(2, 9);
- };
- UserSession.prototype.updateActivity = function() {
- this.lastActivity = new Date();
- };
- UserSession.prototype.getSessionInfo = function() {
- return {
- sessionId: this.sessionId,
- user: this.user,
- loginTime: formatDateToString(this.loginTime),
- lastActivity: formatDateToString(this.lastActivity),
- isActive: this.isSessionActive()
- };
- };
- UserSession.prototype.isSessionActive = function() {
- var now = new Date();
- var timeDiff = now - this.lastActivity;
- return timeDiff < 30 * 60 * 1000; // 30·ÖÖÓÎ޻ÊÓΪ¹ýÆÚ
- };
- UserSession.prototype.serialize = function() {
- var self = this;
- return JSON.stringify(this, function(key, value) {
- if (key === 'loginTime' || key === 'lastActivity') {
- return formatDateToString(value);
- }
- // ±ÜÃâÐòÁл¯ÔÐÍÁ´Éϵķ½·¨
- if (typeof value === 'function') {
- return undefined;
- }
- return value;
- });
- };
- UserSession.prototype.deserialize = function(jsonString) {
- try {
- var data = JSON.parse(jsonString);
- this.user = data.user;
- this.loginTime = parseDateFromString(data.loginTime);
- this.lastActivity = parseDateFromString(data.lastActivity);
- this.sessionId = data.sessionId;
- return true;
- } catch (err) {
- printl("»á»°·´ÐòÁл¯´íÎó:", err);
- print.log("»Ö¸´»á»°Ê§°Ü:", err);
- return false;
- }
- };
- printl("UserSessionÀàÒѶ¨Òå");
- print.log("°üº¬ÐòÁл¯¡¢·´ÐòÁл¯µÈ·½·¨");
- // ´´½¨Óû§»á»°
- var userData = {
- id: 1001,
- username: 'aiwrok_dev',
- permissions: ['read', 'write', 'admin']
- };
- var session = new UserSession(userData);
- printl("´´½¨Óû§»á»°:", session.getSessionInfo());
- print.log("session¶ÔÏó:", session.getSessionInfo());
- // ±£´æ»á»°µ½±¾µØ´æ´¢
- var sessionJson = session.serialize();
- printl("ÐòÁл¯ºóµÄ»á»°Êý¾Ý:", sessionJson);
- print.log("session.serialize():", sessionJson);
- var mockStorage = {
- data: {},
- setItem: function(key, value) {
- this.data[key] = value;
- },
- getItem: function(key) {
- return this.data[key];
- }
- };
- mockStorage.setItem('aiwrok_user_session', sessionJson);
- printl("»á»°Êý¾ÝÒѱ£´æµ½´æ´¢");
- print.log("±£´æµ½localStorageÄ£Äâ");
- // ´Ó±¾µØ´æ´¢»Ö¸´»á»°
- var restoredSession = new UserSession({});
- var sessionData = mockStorage.getItem('aiwrok_user_session');
- if (restoredSession.deserialize(sessionData)) {
- printl("»á»°»Ö¸´³É¹¦:", restoredSession.getSessionInfo());
- print.log("»á»°»Ö¸´³É¹¦:", restoredSession.getSessionInfo());
- } else {
- printl("»á»°»Ö¸´Ê§°Ü");
- print.log("»Ö¸´Ê§°Ü£¬¿ÉÄÜÊÇÊý¾ÝËð»µ");
- }
- // ==================== 9. ÏîÄ¿ÅäÖùÜÀí ====================
- printl("");
- print.log("=== 9. ÏîÄ¿ÅäÖùÜÀí ===");
- // ÏîÄ¿ÅäÖÃÀà
- function ProjectConfig() {
- this.configs = {};
- }
- ProjectConfig.prototype.save = function(name, config) {
- this.configs[name] = config;
- };
- ProjectConfig.prototype.get = function(name) {
- return this.configs[name] || null;
- };
- ProjectConfig.prototype.getAll = function() {
- return this.configs;
- };
- printl("ProjectConfigÀàÒѶ¨Òå");
- print.log("ÅäÖùÜÀíÀà: save, get, getAll·½·¨");
- var projectConfig = {
- name: 'AIWROK IDE Project',
- version: '2.1.0',
- created: new Date('2023-06-01'),
- lastModified: new Date(),
- features: {
- darkMode: true,
- autoSave: true,
- intelliSense: true,
- codeFormatting: true
- },
- dependencies: {
- core: ['react', 'react-native'],
- dev: ['jest', 'eslint', 'prettier'],
- ui: ['react-native-vector-icons', 'react-native-gesture-handler']
- }
- };
- printl("ÏîÄ¿ÅäÖöÔÏó:", projectConfig);
- print.log("°üº¬Date¶ÔÏóºÍǶÌ×¶ÔÏó");
- // ±£´æÏîÄ¿ÅäÖõ½±¾µØ´æ´¢
- function saveProjectConfig(config) {
- var serialized = JSON.stringify(config, function(key, value) {
- if (value instanceof Date) {
- return formatDateToString(value);
- }
- return value;
- }, 2);
-
- // Ä£Äâ localStorage ±£´æ
- mockStorage.setItem('aiwrok_project_config', serialized);
- return serialized;
- }
- // ¼ÓÔØÏîÄ¿ÅäÖÃ
- function loadProjectConfig() {
- var stored = mockStorage.getItem('aiwrok_project_config');
- if (!stored) return null;
-
- try {
- return JSON.parse(stored, function(key, value) {
- // ×Ô¶¯×ª»»ÈÕÆÚ×Ö·û´®Îª Date ¶ÔÏó
- if (key === 'created' || key === 'lastModified') {
- return parseDateFromString(value);
- }
- return value;
- });
- } catch (err) {
- printl("¼ÓÔØÅäÖôíÎó:", err);
- print.log("ÅäÖýâÎöʧ°Ü:", err);
- return null;
- }
- }
- printl("ÅäÖñ£´æºÍ¼ÓÔØº¯ÊýÒѶ¨Òå");
- print.log("×Ô¶¯´¦ÀíDate¶ÔÏóת»»");
- var savedConfig = saveProjectConfig(projectConfig);
- printl("±£´æÅäÖýá¹û:", savedConfig);
- print.log("saveProjectConfig·µ»Ø:", savedConfig);
- var loadedConfig = loadProjectConfig();
- printl("¼ÓÔØÅäÖýá¹û:", loadedConfig);
- print.log("loadProjectConfig·µ»Ø:", loadedConfig);
- if (loadedConfig && loadedConfig.created instanceof Date) {
- printl("Date¶ÔÏó»Ö¸´³É¹¦");
- print.log("loadedConfig.createdÊÇDate¶ÔÏó:", loadedConfig.created);
- } else {
- printl("Date¶ÔÏó»Ö¸´Ê§°Ü");
- print.log("loadedConfig.created²»ÊÇDate¶ÔÏó");
- }
- // ==================== 10. ´úÂëÆ¬¶Î¹ÜÀí ====================
- printl("");
- print.log("=== 10. ´úÂëÆ¬¶Î¹ÜÀí ===");
- // ´úÂëÆ¬¶Î´æ´¢
- function CodeSnippetManager() {
- this.snippets = [];
- }
- CodeSnippetManager.prototype.addSnippet = function(name, language, code, description) {
- description = description === undefined ? '' : description;
- var snippet = {
- id: Date.now(),
- name: name,
- language: language,
- code: code,
- description: description,
- createdAt: new Date(),
- tags: this.extractTags(code)
- };
-
- this.snippets.push(snippet);
- return snippet;
- };
- CodeSnippetManager.prototype.extractTags = function(code) {
- var commonPatterns = {
- 'React': /import.*from\s+['"]react['"]/,
- 'React Native': /from\s+['"]react-native['"]/,
- 'API': /fetch\(|axios\./,
- 'Async': /async\s+|await\s+/,
- 'ES6': /const\s+|let\s+|=>/
- };
-
- var tags = [];
- for (var keyword in commonPatterns) {
- if (commonPatterns.hasOwnProperty(keyword) && commonPatterns[keyword].test(code)) {
- tags.push(keyword.toLowerCase());
- }
- }
- return tags;
- };
- CodeSnippetManager.prototype.searchSnippets = function(keyword) {
- return this.snippets.filter(function(snippet) {
- return snippet.name.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
- snippet.code.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
- snippet.description.toLowerCase().indexOf(keyword.toLowerCase()) !== -1 ||
- snippet.tags.some(function(tag) { return tag.indexOf(keyword.toLowerCase()) !== -1; });
- });
- };
- CodeSnippetManager.prototype.exportSnippets = function() {
- return JSON.stringify(this.snippets, function(key, value) {
- if (key === 'createdAt') {
- return formatDateToString(value);
- }
- return value;
- }, 2);
- };
- CodeSnippetManager.prototype.importSnippets = function(jsonString) {
- try {
- var snippets = JSON.parse(jsonString, function(key, value) {
- if (key === 'createdAt') {
- return parseDateFromString(value);
- }
- return value;
- });
-
- this.snippets = snippets;
- return true;
- } catch (err) {
- printl("µ¼Èë´úÂëÆ¬¶Î´íÎó:", err);
- print.log("µ¼Èëʧ°Ü:", err);
- return false;
- }
- };
- CodeSnippetManager.prototype.saveToStorage = function() {
- var data = {
- snippets: this.snippets,
- exportedAt: new Date()
- };
- var serialized = JSON.stringify(data, function(key, value) {
- if (value instanceof Date) {
- return formatDateToString(value);
- }
- return value;
- }, 2);
- mockStorage.setItem('aiwrok_code_snippets', serialized);
- };
- CodeSnippetManager.prototype.loadFromStorage = function() {
- var stored = mockStorage.getItem('aiwrok_code_snippets');
- if (!stored) return false;
-
- try {
- var data = JSON.parse(stored, function(key, value) {
- if (key === 'exportedAt' || key === 'createdAt') {
- return parseDateFromString(value);
- }
- return value;
- });
-
- this.snippets = data.snippets;
- return true;
- } catch (err) {
- printl("¼ÓÔØ´úÂëÆ¬¶Î´íÎó:", err);
- print.log("¼ÓÔØÊ§°Ü:", err);
- return false;
- }
- };
- printl("CodeSnippetManagerÀàÒѶ¨Òå");
- print.log("°üº¬Ìí¼Ó¡¢ËÑË÷¡¢µ¼Èëµ¼³öµÈ¹¦ÄÜ");
- // ´´½¨´úÂëÆ¬¶Î¹ÜÀíÆ÷
- var snippetManager = new CodeSnippetManager();
- printl("´´½¨´úÂëÆ¬¶Î¹ÜÀíÆ÷");
- print.log("snippetManagerʵÀýÒÑ´´½¨");
- // Ìí¼ÓʾÀý´úÂëÆ¬¶Î
- var snippet1 = snippetManager.addSnippet(
- 'React Hook',
- 'javascript',
- '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;',
- 'React ×é¼þÄ£°å (ES5 °æ±¾)'
- );
- printl("Ìí¼Ó´úÂëÆ¬¶Î1:", snippet1.name);
- print.log("snippet1:", snippet1.name);
- var snippet2 = snippetManager.addSnippet(
- 'API ¿Í»§¶Ë',
- 'javascript',
- '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\');',
- 'ͨÓà API ¿Í»§¶ËÀà (ES5 °æ±¾)'
- );
- printl("Ìí¼Ó´úÂëÆ¬¶Î2:", snippet2.name);
- print.log("snippet2:", snippet2.name);
- // ±£´æµ½±¾µØ´æ´¢
- snippetManager.saveToStorage();
- printl("´úÂëÆ¬¶ÎÒѱ£´æµ½´æ´¢");
- print.log("±£´æµ½localStorageÄ£Äâ");
- // ËÑË÷¹¦ÄܲâÊÔ
- var searchResults = snippetManager.searchSnippets('react');
- printl("ËÑË÷'react'µÄ½á¹û:", searchResults.length, "¸öƬ¶Î");
- print.log("ËÑË÷½á¹û:", searchResults.length);
- // µ¼³ö´úÂëÆ¬¶Î
- var exportedSnippets = snippetManager.exportSnippets();
- printl("µ¼³öµÄ´úÂëÆ¬¶ÎJSON:", exportedSnippets);
- print.log("exportSnippets():", exportedSnippets);
- // ==================== 11. ÐÔÄܶԱÈÑÝʾ ====================
- printl("");
- print.log("=== 11. ÐÔÄܶԱÈÑÝʾ ===");
- // ´´½¨²âÊÔÊý¾Ý
- var testData = {
- largeArray: [],
- summary: {
- total: 1000,
- active: 500,
- inactive: 500
- }
- };
- printl("´´½¨²âÊÔÊý¾Ý¶ÔÏó");
- print.log("°üº¬1000¸öÏîÄ¿µÄÊý×é");
- for (var k = 0; k < 1000; k++) {
- testData.largeArray.push({
- id: k,
- name: 'ÏîÄ¿ ' + k,
- status: k % 2 === 0 ? 'active' : 'inactive',
- metadata: {
- created: new Date(),
- tags: ['tag1', 'tag2', 'tag3'],
- config: { enabled: true, priority: k }
- }
- });
- }
- printl("²âÊÔÊý¾Ý´´½¨Íê³É£¬¹²", testData.largeArray.length, "¸öÏîÄ¿");
- print.log("testData°üº¬", testData.largeArray.length, "¸öÏîÄ¿");
- // ²âÊÔÐòÁл¯ÐÔÄÜ
- var startTime = Date.now();
- var serializedLarge = JSON.stringify(testData);
- var serializeTime = Date.now() - startTime;
- printl("ÐòÁл¯ºÄʱ:", serializeTime, "ºÁÃë");
- print.log("JSON.stringifyºÄʱ:", serializeTime, "ms");
- var startTime2 = Date.now();
- var deserializedLarge = JSON.parse(serializedLarge);
- var deserializeTime = Date.now() - startTime2;
- printl("·´ÐòÁл¯ºÄʱ:", deserializeTime, "ºÁÃë");
- print.log("JSON.parseºÄʱ:", deserializeTime, "ms");
- printl("×ܺÄʱ:", serializeTime + deserializeTime, "ºÁÃë");
- print.log("ÍêÕûJSON²Ù×÷×ܺÄʱ:", serializeTime + deserializeTime, "ms");
- // ==================== 12. JSON ¹¤¾ßº¯Êý ====================
- printl("");
- print.log("=== 12. JSON ¹¤¾ßº¯Êý ===");
- function JsonUtils() {}
- JsonUtils.isValidJSON = function(str) {
- try {
- JSON.parse(str);
- return true;
- } catch (e) {
- return false;
- }
- };
- JsonUtils.safeStringify = function(obj, fallback, replacer) {
- fallback = fallback === undefined ? '{}' : fallback;
- replacer = replacer === undefined ? null : replacer;
- try {
- return JSON.stringify(obj, replacer, 2);
- } catch (err) {
- printl("safeStringify´íÎó:", err);
- print.log("°²È«ÐòÁл¯Ê§°Ü:", err);
- return fallback;
- }
- };
- JsonUtils.safeParse = function(str, fallback, reviver) {
- fallback = fallback === undefined ? null : fallback;
- reviver = reviver === undefined ? null : reviver;
- try {
- return JSON.parse(str, reviver);
- } catch (err) {
- printl("safeParse´íÎó:", err);
- print.log("°²È«½âÎöʧ°Ü:", err);
- return fallback;
- }
- };
- JsonUtils.validateObjectStructure = function(obj, requiredFields) {
- var missing = [];
- var invalid = [];
-
- for (var m = 0; m < requiredFields.length; m++) {
- var field = requiredFields[m];
- if (!(field in obj)) {
- missing.push(field);
- } else if (obj[field] === null || obj[field] === undefined || obj[field] === '') {
- invalid.push(field);
- }
- }
-
- return {
- isValid: missing.length === 0 && invalid.length === 0,
- missing: missing,
- invalid: invalid
- };
- };
- printl("JsonUtils¹¤¾ßÀàÒѶ¨Òå");
- print.log("°üº¬isValidJSON, safeStringify, safeParse, validateObjectStructure");
- // ²âÊÔ JSON ¹¤¾ß
- var testValidJSON = '{"name": "AIWROK", "version": "1.0.0"}';
- var testInvalidJSON = '{"name": "AIWROK", "version": }';
- printl("²âÊÔÓÐЧJSON:", testValidJSON);
- print.log("testValidJSON:", testValidJSON);
- var validResult = JsonUtils.isValidJSON(testValidJSON);
- printl("ÓÐЧJSONÑéÖ¤½á¹û:", validResult);
- print.log("JsonUtils.isValidJSON(testValidJSON):", validResult);
- printl("²âÊÔÎÞЧJSON:", testInvalidJSON);
- print.log("testInvalidJSON:", testInvalidJSON);
- var invalidResult = JsonUtils.isValidJSON(testInvalidJSON);
- printl("ÎÞЧJSONÑéÖ¤½á¹û:", invalidResult);
- print.log("JsonUtils.isValidJSON(testInvalidJSON):", invalidResult);
- var safeParsed = JsonUtils.safeParse(testInvalidJSON, { error: true });
- printl("°²È«½âÎö½á¹û:", safeParsed);
- print.log("JsonUtils.safeParse(testInvalidJSON):", safeParsed);
- var testObj = { name: 'AIWROK', version: '1.0.0' };
- var required = ['name', 'version', 'author'];
- var validation = JsonUtils.validateObjectStructure(testObj, required);
- printl("¶ÔÏó½á¹¹ÑéÖ¤:", validation);
- print.log("JsonUtils.validateObjectStructure:", validation);
- printl("");
- print.log("=== JSON´¦ÀíÍêÕûʾÀýÍê³É ===");
- printl("💡 ÕâЩ¼¼ÇÉÔÚʵ¼ÊÏîÄ¿¿ª·¢Öзdz£ÓÐÓã¡");
- print.log("ËùÓÐJSON²Ù×÷ʾÀýÒÑÍê³É£¡");
¸´ÖÆ´úÂë
|
|