1 /* See license.txt for terms of usage */ 2 3 define([ 4 "firebug/lib/trace" 5 ], 6 function(FBTrace) { 7 8 // ********************************************************************************************* // 9 // Constants 10 11 var Ci = Components.interfaces; 12 var Cc = Components.classes; 13 var Cu = Components.utils; 14 15 var Json = {}; 16 17 // ********************************************************************************************* // 18 // JSON 19 20 // xxxFlorent: What is the advantages of this method over JSON.parse ? 21 Json.parseJSONString = function(jsonString, originURL) 22 { 23 if (FBTrace.DBG_JSONVIEWER) 24 FBTrace.sysout("jsonviewer.parseJSON; " + jsonString); 25 26 // See if this is a Prototype style *-secure request. 27 var regex = new RegExp(/\s*\/\*-secure-([\s\S]*)\*\/\s*$/); 28 var matches = regex.exec(jsonString); 29 30 if (matches) 31 { 32 jsonString = matches[1]; 33 34 // removes the Newline escaped caracters at the beginning and at the end of the string 35 jsonString = jsonString.replace(/(^\\n|\\n$)/g, ""); 36 /*if (jsonString[0] == "\\" && jsonString[1] == "n") 37 jsonString = jsonString.substr(2); 38 39 if (jsonString[jsonString.length-2] == "\\" && jsonString[jsonString.length-1] == "n") 40 jsonString = jsonString.substr(0, jsonString.length-2);*/ 41 } 42 43 if (jsonString.indexOf("&&&START&&&")) 44 { 45 regex = new RegExp(/&&&START&&& (.+) &&&END&&&/); 46 matches = regex.exec(jsonString); 47 if (matches) 48 jsonString = matches[1]; 49 } 50 51 try 52 { 53 var s = Components.utils.Sandbox(originURL); 54 55 // throw on the extra parentheses 56 return Components.utils.evalInSandbox("(" + jsonString + ")", s); 57 } 58 catch(e) 59 { 60 if (FBTrace.DBG_JSONVIEWER) 61 FBTrace.sysout("jsonviewer.parseJSON FAILS on "+originURL+" for \""+jsonString+ 62 "\" with EXCEPTION "+e, e); 63 } 64 65 // Let's try to parse it as JSONP. 66 var reJSONP = /^\s*([A-Za-z0-9_.]+\s*(?:\[.*\]|))\s*\(.*\)/; 67 var m = reJSONP.exec(jsonString); 68 if (!m || !m[1]) 69 return null; 70 71 if (FBTrace.DBG_JSONVIEWER) 72 FBTrace.sysout("jsonviewer.parseJSONP; " + jsonString); 73 74 var callbackName = m[1]; 75 76 if (FBTrace.DBG_JSONVIEWER) 77 FBTrace.sysout("jsonviewer.parseJSONP; Look like we have a JSONP callback: " + callbackName); 78 79 // Replace the original callback (it can be e.g. foo.bar[1]) with simple function name. 80 jsonString = jsonString.replace(callbackName, "callback"); 81 82 try 83 { 84 var s = Components.utils.Sandbox(originURL); 85 s["callback"] = function(object) { return object; }; 86 return Components.utils.evalInSandbox(jsonString, s); 87 } 88 catch(ex) 89 { 90 if (FBTrace.DBG_JSONVIEWER) 91 FBTrace.sysout("jsonviewer.parseJSON EXCEPTION", e); 92 } 93 94 return null; 95 }; 96 97 // ********************************************************************************************* // 98 99 return Json; 100 101 // ********************************************************************************************* // 102 }); 103