-
Notifications
You must be signed in to change notification settings - Fork 11
/
fmt2json.min.js
7 lines (7 loc) · 10.9 KB
/
fmt2json.min.js
1
2
3
4
5
6
7
/**
* @license
* format-to-json v3.0.5
* GitHub Repository <https://github.com/CN-Tower/format-to-json>
* Released under MIT license <https://github.com/CN-Tower/format-to-json/blob/master/LICENSE>
*/
!function(root){var performance=("object"==typeof window?window:eval("require('perf_hooks')")).performance,BREAK="\r\n",SPACE=" ",OPTIONS={indent:2,isExpand:!0,isStrict:!1,isEscape:!1,isUnscape:!1,keyQtMark:'"',valQtMark:'"'},ESCAPES_MAP=[{ptn:/\r\n/gm,str:""},{ptn:/\n\r/gm,str:""},{ptn:/\n/gm,str:"\\n"},{ptn:/\r/gm,str:"\\r"},{ptn://gm,str:"\\b"},{ptn://gm,str:"\\v"},{ptn:/\f/gm,str:"\\f"},{ptn:/\t/gm,str:"\\t"}],MESSAGES_MAP={err:function(){return"Parse Error, an excessive abnormal Json!"},war:function(e){return"Formated ".concat(e," lines, abnormal JSON source!")},scc:function(e){return"Success formated ".concat(e," lines!")},val:function(e){return"Invalid value in line: ".concat(e)},ost:function(e){return"Expect a string in line: ".concat(e)},col:function(e){return"Expect a colon in line: ".concat(e)},end:function(e,t){return'Expect a comma or a "'.concat(t,'" in line: ').concat(e)}};function fmt2json(source,options){var startTime=performance.now(),fmtSource=source,curLevel=0,curIndex=1,exceptType="",exceptSign="",signsQueue="",baseIndent="",isSrcValid=!0,isFmtError=!1,withDetails=!1,fmtResult="",fmtType="info",fmtSign="",fmtLines=0,message="",errFormat=!1,errNear="",errIndex=NaN,errExpect="",fmtOptions=Object.assign({},OPTIONS);options&&("boolean"==typeof options.withDetails&&(withDetails=options.withDetails),"boolean"==typeof options.expand&&(fmtOptions.isExpand=options.expand),"boolean"==typeof options.strict&&(fmtOptions.isStrict=options.strict),"boolean"==typeof options.escape&&(fmtOptions.isEscape=options.escape),"boolean"==typeof options.unscape&&(fmtOptions.isUnscape=options.unscape),"number"==typeof options.indent&&0<options.indent&&(fmtOptions.indent=options.indent),-1<["'",'"',""].indexOf(options.keyQtMark)&&(fmtOptions.keyQtMark=options.keyQtMark),-1<["'",'"'].indexOf(options.valQtMark))&&(fmtOptions.valQtMark=options.valQtMark),baseIndent=getBaseIndent();try{try{""!==fmtSource&&eval("fmtSource = ".concat(fmtSource)),""===fmtSource||-1<["object","boolean"].indexOf(typeof fmtSource)?doNormalFormat(fmtSource):(fmtOptions.isUnscape&&(fmtSource=fmtSource.replace(/\\"/gm,'"').replace(/\\\\/gm,"\\")),doSpecialFormat())}catch(err){fmtOptions.isUnscape&&(fmtSource=fmtSource.replace(/\\"/gm,'"').replace(/\\\\/gm,"\\")),doSpecialFormat()}}catch(err){isFmtError=!0}finally{return setFmtStatus(),withDetails?{result:fmtResult,fmtType:fmtType,fmtSign:fmtSign,fmtLines:fmtLines,fmtTime:performance.now()-startTime,message:message,errFormat:errFormat,errIndex:errIndex,errNear:errNear,errExpect:errExpect}:fmtResult}function doNormalFormat(e){if(-1<[!0,!1,null,""].indexOf(e))return fmtResult+=String(e);((e=fmtOptions.isStrict?JSON.parse(JSON.stringify(e)):e)instanceof Array?arrayHandler:objectHandler)(e)}function arrayHandler(e){var t;if(0<e.length){fmtResult+=brkLine4Normal("["),curLevel++;for(var r=0;r<e.length;r++)t=fmtOptions.isExpand?getCurIndent():"",fmtResult+=t,valueHandler(e[r]),fmtResult+=brkLine4Normal(r<e.length-1?",":"");curLevel--,t=fmtOptions.isExpand?getCurIndent():"",fmtResult+=t+"]"}else fmtResult+="[]"}function objectHandler(e){var t=Object.keys(e);if(0<t.length){var r,n=0;for(r in fmtResult+=brkLine4Normal("{"),curLevel++,e){n++;var c=quoteNormalStr(r,fmtOptions.keyQtMark),s=fmtOptions.isExpand?getCurIndent():"";fmtResult=(fmtResult=fmtResult+s+c)+(fmtOptions.isExpand?": ":":"),valueHandler(e[r]),fmtResult+=brkLine4Normal(n<t.length?",":"")}curLevel--,s=fmtOptions.isExpand?getCurIndent():"",fmtResult+=s+"}"}else fmtResult+="{}"}function valueHandler(e){switch(typeof e){case"undefined":case"function":return fmtResult+=String(e);case"number":case"boolean":return fmtResult+=e;case"object":return doNormalFormat(e);case"string":fmtResult+=quoteNormalStr(e,fmtOptions.valQtMark)}}function doSpecialFormat(){if(0!==(fmtSource=fmtSource.replace(/^\s*/,"")).length){var e,t=!1;switch(fmtSource[0]){case"'":case'"':t=!0,quotaHandler();break;case":":t=!0,colonHandler();break;case",":t=!0,commaHandler();break;case"{":t=!0,objPreHandler();break;case"}":t=!0,objEndHandler();break;case"[":t=!0,arrPreHandler();break;case"]":t=!0,arrEndHandler();break;case"(":t=!0,tupPreHandler();break;case")":t=!0,tupEndHandler()}return t||(e=fmtSource.match(/^u(\s)?'|^u(\s)?"/))&&(t=!0,unicHandler(e[0])),t||(e=fmtSource.match(/^(-?[0-9]+\.?[0-9]*|0[xX][0-9a-fA-F]+)/))&&(t=!0,numbHandler(e[0])),t||(e=fmtSource.match(/^(true|false|True|False)/))&&(t=!0,boolHandler(e[0])),t||(e=fmtSource.match(/^(null|undefined|None|NaN)/))&&(t=!0,nullHandler(e[0])),t||otheHandler(),doSpecialFormat()}}function quotaHandler(){var e=getSrcRest(),e=getNextQuotaIndex(fmtSource[0],e),t=(chkFmtExpect(fmtSource[0]),fmtSource.substr(0,1)),r="ost"===exceptType,n="";fmtSource=-1<e?(n=fmtSource.substr(1,e),fmtResult+=quoteSpecialStr(n,t,r),setFmtExpect(fmtSource[0]),getSrcRest(e+2)):(n=fmtSource.substr(1),fmtResult+=quoteSpecialStr(n,t,r),setFmtExpect("!"),"")}function colonHandler(){fmtResult+=fmtOptions.isExpand?": ":":",chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=getSrcRest()}function commaHandler(){var e=getCurIndent();fmtOptions.isExpand&&curIndex++,fmtResult+=fmtOptions.isExpand?",".concat(BREAK+e):",",chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),""===(fmtSource=getSrcRest()).replace(/(\r)?\n|\s/gm,"")&&setFmtError("val")}function objPreHandler(){chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=fmtSource[1]&&"}"===fmtSource[1]?(fmtResult+="{}",setFmtExpect("}"),getSrcRest(2)):(curLevel++,fmtResult+="{",brkLine4Special(),getSrcRest())}function objEndHandler(){curLevel--,brkLine4Special("}"),chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=getSrcRest()}function arrPreHandler(){chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=fmtSource[1]&&"]"===fmtSource[1]?(fmtResult+="[]",setFmtExpect("]"),getSrcRest(2)):(curLevel++,fmtResult+="[",brkLine4Special(),getSrcRest())}function arrEndHandler(){curLevel--,brkLine4Special("]"),chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=getSrcRest()}function tupPreHandler(){chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=fmtSource[1]&&")"===fmtSource[1]?(fmtResult+=fmtOptions.isStrict?"[]":"()",setFmtExpect(")"),getSrcRest(2)):(curLevel++,fmtResult+=fmtOptions.isStrict?"[":"(",brkLine4Special(),getSrcRest())}function tupEndHandler(){curLevel--,brkLine4Special(fmtOptions.isStrict?"]":")"),chkFmtExpect(fmtSource[0]),setFmtExpect(fmtSource[0]),fmtSource=getSrcRest()}function unicHandler(e){var t=getSrcRest(e.length),t=-1<e.indexOf("'")?getNextQuotaIndex("'",t):getNextQuotaIndex('"',t),r=(chkFmtExpect("u"),"ost"===exceptType),n="";fmtSource=-1<t?(t=t+e.length+1,n=fmtSource.substr(e.length,t-e.length-1),fmtResult+=quoteSpecialStr(n,e,r),setFmtExpect("u"),getSrcRest(t)):(n=fmtSource.substr(e.length),fmtResult+=quoteSpecialStr(n,e,r),setFmtExpect("!"),"")}function numbHandler(e){fmtResult+=e,chkFmtExpect("n"),setFmtExpect("n"),fmtSource=getSrcRest(e.length)}function boolHandler(e){fmtResult+=fmtOptions.isStrict?e.toLowerCase():e,chkFmtExpect("b"),setFmtExpect("b"),fmtSource=getSrcRest(e.length)}function nullHandler(e){fmtResult+=fmtOptions.isStrict?"null":e,chkFmtExpect("N"),setFmtExpect("N"),fmtSource=getSrcRest(e.length)}function otheHandler(){var e=fmtSource.match(/^[^\{\}\[\]\(\):,]*/),e=e&&e[0]||"";e&&(fmtResult+=e,chkFmtExpect("!"),fmtSource=getSrcRest(e.length))}function chkFmtExpect(e){if(isSrcValid)switch(exceptType){case"val":-1<":,}])!".indexOf(e)&&setFmtError("val");break;case"ost":-1==="'\"unbN".indexOf(e)&&setFmtError("ost");break;case"end":var t=getBracketPair(exceptSign);-1===[",",t].indexOf(e)&&setFmtError("end",t);break;case"col":":"!==e&&setFmtError("col")}}function setFmtExpect(e){switch(e){case":":exceptType="val";break;case",":exceptType="{"===exceptSign?"ost":"val";break;case"{":signsQueue+=exceptSign=e,exceptType="ost";break;case"}":signsQueue=signsQueue.substr(0,signsQueue.length-1),exceptSign=signsQueue.substr(-1),exceptType="end";break;case"[":signsQueue+=exceptSign=e,exceptType="val";break;case"]":signsQueue=signsQueue.substr(0,signsQueue.length-1),exceptSign=signsQueue.substr(-1),exceptType="end";break;case"(":signsQueue+=exceptSign=e,exceptType="val";break;case")":signsQueue=signsQueue.substr(0,signsQueue.length-1),exceptSign=signsQueue.substr(-1),exceptType="end";break;case"u":case"n":case"b":case"N":case'"':case"'":exceptType="ost"===exceptType?"col":"end"}}function setFmtError(e){var t,r,n=1<arguments.length&&void 0!==arguments[1]?arguments[1]:"";switch(e){case"war":fmtType="warning";break;case"scc":fmtType="success";break;default:fmtType="danger"}-1<["ost","col","val","end"].indexOf(e)&&(isSrcValid=!(errFormat=!0),errExpect=n,errIndex=curIndex,t=fmtResult.substr(-20).replace(/^(\s|\n|\r\n)*/,"").replace(/(\n|\r\n)/gm,"\\n"),r=fmtSource.substr(0,10).replace(/(\s|\n|\r\n)*$/,"").replace(/(\n|\r\n)/gm,"\\n"),errNear="...".concat(t,">>>>>>").concat(r)),message=MESSAGES_MAP[fmtSign=e](curIndex,n)}function setFmtStatus(){isFmtError&&!errIndex?(setFmtError("err"),errFormat=!0):isSrcValid&&(signsQueue?setFmtError("end",getBracketPair(signsQueue.substr(-1))):setFmtError("scc")),fmtLines=curIndex}function brkLine4Normal(e){return fmtOptions.isExpand?(curIndex++,e+BREAK):e}function brkLine4Special(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:"";if(!fmtOptions.isExpand)return fmtResult+=e;curIndex++,fmtResult+=BREAK+getCurIndent()+e}function quoteNormalStr(t,e){var r=2<arguments.length&&void 0!==arguments[2]&&arguments[2],n=fmtOptions.isEscape&&'"'===fmtOptions.keyQtMark&&'"'===e&&(!r||fmtOptions.isStrict),c=(t=r?t.replace(/(?!\\[b|f|n|\\|r|t|x|v|'|"|0])\\/gm,"\\\\"):t.replace(/\\/gm,"\\\\"),ESCAPES_MAP.forEach(function(e){return t=t.replace(e.ptn,e.str)}),n?"\\".concat(e):e);switch(n&&(t=t.replace(/\\/gm,"\\\\")),e){case'"':return c+(t=n?t.replace(/"/gm,'\\\\\\"'):t.replace(/"/gm,'\\"'))+c;case"'":return c+(t=t.replace(/'/gm,"\\'"))+c;default:return t}}function quoteSpecialStr(e,t,r){r=r?fmtOptions.keyQtMark:fmtOptions.valQtMark;return e=quoteNormalStr(e=(e=(e=e.replace(/(?!\\[b|f|n|\\|r|t|x|v|'|"|0])\\/gm,"")).replace(/\\\"/gm,'"')).replace(/\\\'/gm,"'"),r,!0),e=!fmtOptions.isStrict&&1<t.length?t.substr(0,t.length-1)+e:e}function getSrcRest(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:1;return fmtSource.length>e?fmtSource.substr(e):""}function getNextQuotaIndex(e,t){for(var r=0;r<t.length;r++)if(t[r]===e&&(0===r||"\\"!==t[r-1]||"\\"===t[r-1]&&"\\"===t[r-2]&&"\\"!==t[r-3]))return r;return-1}function getBaseIndent(){for(var e="",t=0;t<fmtOptions.indent;t++)e+=SPACE;return e}function getCurIndent(){for(var e="",t=0;t<curLevel;t++)e+=baseIndent;return e}function getBracketPair(e){var t=["{","[","("],r=["}","]",")"],n=t.indexOf(e),e=r.indexOf(e);return-1<n?r[n]:t[e]}}"function"==typeof define&&define.amd?define(function(){return fmt2json}):"object"==typeof exports?module.exports=fmt2json:root.fmt2json=fmt2json}(this);