1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// string -> string  `"${string}"`
// number -> `${number}`
// bigInt -> throw new Error('Do not know how to serialize a BigInt at JSON.stringify');
// infinity -> null
// -infinity-> null
// boolean -> `${boolean}`
// undefined -> undefined null
// null -> null
// symbol  -> undefined
// function -> undefined
// date  Fri Sep 10 2021 11:05:07 GMT+0800 (中国标准时间) -> `${date.toISOString()}` ""2021-09-10T03:04:48.870Z""
// regExp -> "{}"
// error -> "{}"
// array ->
// object->
function isType(data, type) {
  const typeStr = Object.prototype.toString.call(data);
  const reg = /\s([A-z]+)\]/g;
  const matchs = reg.exec(typeStr);
  return matchs[1].toLowerCase() === type.toLowerCase();
}
function stringify(data) {
  if(isType(data, "bigInt")) { // 报错的数据类型
    throw new Error('Do not know how to serialize a BigInt at JSON.stringify');
  }
 
  const nullTypes = ["undefined", "infinity", "-infinity", "null"]
  if(nullTypes.some(v => isType(data,v))) { // 返回null的数据类型
    return "null"
  }
  if(data !== data) {
    return 'null';
  }
  const undefinedTypes = [ "symbol", "function"]
  if(undefinedTypes.some(v => isType(data,v))) { // 返回undefined的数据类型
    return "undefined"
  }
  const originalTypes = ["number", "boolean"]
  if(originalTypes.some(v => isType(data,v))) { // 返回原数据的数据类型
    return `${data}`
  }
  if(isType(data, "string")) { // 处理 string
    return `"${data}"`
  }
  const emptyObjTypes = ["regexp", "error"]
  if(emptyObjTypes.some(v => isType(data,v))) { // 返回{}的数据类型
    return `{}`
  }
  if(isType(data, "date")) { // 处理date
    return `${data.toISOString()}`;
  }
  if (Array.isArray(data)) {  // 处理数组
    const arr = data.map(v => stringify(v));
    return `[${arr.join(",")}]`
  }
  if(isType(data,"object")) { // 处理对象
    const arr = Object.entries(data).reduce((cur, [key, value]) => {
      if(value === undefined) { return cur};
      cur.push(`"${key}":${stringify(value)}`);
      return cur;
    }, [])
    return `{${arr.join(",")}}`;
  }
}

  

posted on   ygunoil  阅读(203)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示