首页 > 编程知识 正文

js对象转json字符串,并保留js对象中的javascript脚本

时间:2023-05-05 03:50:05 阅读:201286 作者:3561

</pre><pre name="code" class="javascript"> /** * Created by shantao on 2016/2/1. *//** * json对象转字符串 * * @param obj json对象 * @returns */function obj2Str(obj) { switch (typeof (obj)) { case 'object': var ret = []; if (obj instanceof Array) { for ( var i = 0, len = obj.length; i < len; ihldbzhldbz) { ret.push(obj2Str(obj[i])); } return '[' hldbz ret.join(',') hldbz ']'; } else if (obj instanceof RegExp) { return obj.toString(); } else { for ( var a in obj) { ret.push(a hldbz ':' hldbz obj2Str(obj[a])); } return '{' hldbz ret.join(',') hldbz '}'; } case 'function': return obj; case 'number': return obj.toString(); case 'string': return """ hldbz obj.replace(/(\|")/g, "\$1").replace(/n|r|t/g, function(a) { return ("n" == a) ? "\n" : ("r" == a) ? "\r" : ("t" == a) ? "\t" : ""; }) hldbz """; case 'boolean': return obj.toString(); default: return obj.toString(); }}/** * json对象转字符串 * * @param obj json对象 * @param needScript true|false 是否保留json对象中的javaScript脚本 */function formatJsonObjToString(obj, needScript) { var resultString = ""; if (needScript) { resultString = obj2Str(obj); } else { resultString = JSON.stringify(obj); } return resultString;}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。