JSON.stringify⽅法实现JSONFormat.js
/**
* 将对象转为json字符串
*/
class JSONFormat {
/**
* 构造器
* @param obj ⽬标对象
* @param replacer {function|Array}
* @param space {string|number}间隔符
*/
constructor(obj,replacer,space){
this.target = obj;
if(typeof space ==='string'){
this.space = space.length >10? space.substring(0,10): space;
}else if(typeof space ==='number'){
if(space >=10){
//⼤于10,默认是10个空格
this.space ='          ';
}else if(space >=0&& space <10){
//空格数量根据space来确定
this.space =' '.repeat(space);
}
}
//缓存,⽤于存储当前值和上下⽂对象
this.cache =new Map();
}
/**
* 格式化⽅法
* @returns {string} 格式化后的字符串
*/
stringify(){
/
/space第⼀次要置为空
placer && Array.placer)&&placer.length >0){
return this.placer[0],this.target,this.target,'');
}
return this.formatValue('',this.target,this.target,'');
}
/**
* 处理对象类型
* @param obj 对象
* @param space {string} 间隔符
* @returns {string} 对象json字符串
*/
formatObject(obj,space){
let keys = Object.keys(obj);
if(keys.length ===0){
//对象没有属性,返回空对象
return'{}';
}
let jsonStr ='{';
let itemArr =[];
keys.forEach(key =>{
let value =this.formatValue(key,obj[key],obj,space+this.space);
if(value){
let tp ='';
if(this.space){
tp ='\n'+space+this.space;
}
tp +=`\"${key}\":${value}`;
itemArr.push(tp);
itemArr.push(tp);
}
});
//去掉多余的逗号
jsonStr += itemArr.join(',');
if(this.space && itemArr.length >0){
//结束的分隔符不需要再推进⼀层,所以直接拼接space
jsonStr +='\n'+space;
}
jsonStr +='}';
return jsonStr;
}
/**
* 处理数组类型
* @param arr {Array}数组对象
* @param space {string} 间隔符
* @returns {string} 数组json字符串
*/
formatArray(arr,space){
if(arr.length ===0){
//数组为空,返回空数组
return'[]';
}
let jsonStr ='[';
arr.forEach((item,index)=>{
const res =this.formatValue(index,item,arr,space+this.space);
if(res){
if(this.space){
jsonStr +='\n'+space+this.space;
}
jsonStr += res +',';
}
});
//去掉多余的逗号
jsonStr = jsonStr.substring(0,jsonStr.length -1);
if(this.space){
//结束的分隔符不需要再推进⼀层,所以直接拼接space
jsonStr +='\n'+space;
}
jsonStr +=']';
return jsonStr;
}
/**
* 处理数值
* @param value 正在处理的当前值
* @param context 上下⽂,⽤于判断循环引⽤
* @param space {string} 间隔符
* @returns {string} 返回格式化后的字符串
*/
formatValue(key,value,context,space){
placer){
if(placer ==='function'){
return'\"'+placer(key,value)+'\"';
}else placer && Array.placer)){
if(typeof context ==='object'&&!Array.isArray(context)&&!placer.includes(key)){
return;
}
}
}
if(this.cache.has(context)){
if((context)=== value){
//如果有循环引⽤,直接抛出异常,防⽌栈溢出
throw new Error('TypeError: Converting circular structure to JSON');
}
}
}
this.cache.set(value,context);
if(typeof value ==='undefined'||typeof value ==='function'){
//undefined和函数直接返回
return;
}else if(value ==null){
//null类型,直接返回null
return'null';
}else if(typeof value ==='string'){
//字符串类型,需要拼接双引号
value =`\"${value}\"`;
}else if(value instanceof Date){
//Date类型,调⽤toJSON()⽅法,返回⽇期格式字符串
value =`\"${JSON()}\"`;
}else if(value instanceof RegExp){
//正则类型总是返回⼀个空对象
value ='{}';
}else if( Array.isArray(value)){
//数组类型,递归调⽤数组格式化⽅法
value =this.formatArray(value,space);
}else if(typeof value ==='object'){
//普通对象类型,递归调⽤对象格式化⽅法
value =this.formatObject(value,space);
}
//返回处理后的字符串
js获取json的key和valuereturn value;
}
}
exports.JSONFormat = JSONFormat;
JSON.js
const{JSONReader}=require('./JSONReader');
const{JSONParser}=require('./JSONParser');
const{JSONFormat}=require('./JSONFormat');
class JSON {
static stringify(obj,replacer,space){
const jsonFormat =new JSONFormat(obj,replacer,space);
return jsonFormat.stringify();
}
static parse(str){
const jsonReader =new JSONReader(str);
const parser =new kens);
sult;
}
}
exports.JSON=JSON;
index.js
const{JSON}=require('./code/JSON');
const a =[
"a","b",["a","b",["a","b","c"]]
]
let res =JSON.stringify(a,['a'],'\t');
console.log(res);
运⾏结果
[ "a", "b", [ "a", "b", [ "a", "b", "c" ]
]
]

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。