- 首先JSON.stringify()是将js对象转换为JSON形式
实现思路:
通过递归调用,来实现对转换对象Object的深层value进行遍历,利用array的join实现最终字符串拼接
function myJsonStringify(obj) { let type = typeof obj; if (type !== "object" || type === null) { if (/string|undefined|function/.test(type)) { obj = ‘"‘ + obj + ‘"‘; } return String(obj); } else { let json = [], arr = (obj && obj.constructor === Array); for (let k in obj) { let v = obj[k]; let type = typeof v; if (/string|undefined|function/.test(type)) { v = ‘"‘ + v + ‘"‘; } else if (type === "object") { v = myJsonStringify(v); } json.push((arr ? "" : ‘"‘ + k + ‘":‘) + String(v)); } return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}") } }
一个较为完整版的实现:
(function(NS){ var simpleTypes=["number","boolean","undefined","string","function"] function stringify(object){ var type=typeof object if(indexOf(simpleTypes,type)>-1){ return parseSimpleObject(object); } if(object instanceof Array){ var len=object.length; var resArr=[]; for(var i=0;i<len;i++){ var itemType=typeof object[i]; if(indexOf(simpleTypes,itemType)>-1){ if(itemType!="undefined"){ resArr.push(parseSimpleObject(object[i])); } else{ resArr.push(‘null‘) } } else{ resArr.push(stringify(object[i])) } } return "["+resArr.join(",")+ "]" } if(object instanceof Object){ if(object==null){ return "null" } var resArr=[] for(var name in object){ var itemType=typeof object[name]; if(indexOf(simpleTypes,itemType)>-1){ if(itemType!=‘undefined‘){ resArr.push("\"" + name + "\":" + parseSimpleObject(object[name])) } } else{ resArr.push("\"" + name +"\":" +stringify(object[name])) } } return "{" +resArr.join(",") +"}" } } function parseSimpleObject(object){ var type=typeof object; if(type=="string"||type=="function"){ return "\"" + object.toString().replace("\"","\\\"") + "\"" } if(type=="number"||type=="boolean"){ return object.toString() } if(type=="undefined"){ return "undefined" } return "\"" +object.toString().replace("\"","\\\"") +"\"" } function indexOf(arr,val){ for(var i=0;i<arr.length;i++){ if(arr[i]===val){ return i; } } return -1 } NS.stringify=function(object,isEncodeZh){ var res=stringify(object) if(isEncodeZh){ var encodeRes=""; for(var i=0;i<res.length;i++){ if(res.charCodeAt(i)<Oxff){ encodeRes+=res[i] } else{ encodeRes+="\\u"+res.charCodeAt(i).toString(16); } } res=encodeRes } return res; } })(window);
JSON.parse()是将JSON对象转换为js对象
实现方式:(2种)
eval()
var json=‘{"a":"1","b":2}‘ var obj=eval("("+json+")");
直接调用eval,会产生xss漏洞。
利用new Function()
第一种eval的方法,相当于无脑把JSON字符串塞进去,eval和Function都有着动态编译js代码的作用
var func=new Function(arg1,arg2,...,functionBody) var jsonStr=‘{"age":20,"name":"jack"}‘ var json=(new Function(‘return‘+jsonStr))()
原文地址:https://www.cnblogs.com/yuan233/p/10986714.html
时间: 2024-10-04 02:59:20