当前位置: 首页 > news >正文

【JS 算法题: 将 json 转换为字符串】

题目简介

其实就是手撕 JSON.stringfy()。

算法实现

输入

原则上来说,输入的是一个 json 对象。但需要考虑到异常情况,即输入了其它类型的数据,比如:12, true, ‘abc’, [‘red’, ‘green’], null, undefined 等。
在这里插入图片描述

输出

输出一个字符串。

实现

function jsonToString(obj) {if (typeof obj === 'undefined') return undefined;if (typeof obj === 'string') return `"${obj}"`;if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null ) {return String(obj);}if (Array.isArray(obj)) {const arrJson = obj.map(item => jsonToString(item));return `[${arrJson.join(',')}]`;}if (typeof obj === 'object') {const res = []for (const key in obj) {if (obj.hasOwnProperty(key)) { // 对象实例上的属性const valueStr = jsonToString(obj[key]);res.push(`"${key}":${valueStr}`);}}return `{ ${res.join(',')} }`;}
}

测试case

const jsonArr = [1, 2, [3, 4, 5, [3333, 'dd', {name: 'denny', age: {xx: '12'}}], true]];
const jsonObj = {name: 'denny',city: ['sh', 'bj', 'xa'],info: {age: 12,school: {}}
}

相关知识

数据类型转换

数据类型判断

判断一个值是否为对象

数组循环遍历

对象循环遍历

for…in…

遍历对象的可枚举属性(包含继承的可枚举属性)(symbol 除外)

var triangle = { a: 1, b: 2, c: 3 };
function ColoredTriangle() {this.color = "red";
}
ColoredTriangle.prototype = triangle;var obj = new ColoredTriangle();for (var prop in obj) {// if (obj.hasOwnProperty(prop)) {console.log(prop);// }
}

在这里插入图片描述

for (var prop in [1, 2, 3]) {console.log(prop);
}
// 0 1 2

判断对象的实例属性

http://www.lryc.cn/news/310394.html

相关文章:

  • 数的范围 刷题笔记
  • XSS简介及xsslabs第一关
  • 构建安全的REST API:OAuth2和JWT实践
  • 从0开始学习NEON(1)
  • (二十三)Flask之高频面试点
  • 设计模式(十三)抽象工厂模式
  • HTTP Cookie 你了解多少?
  • 【QT+QGIS跨平台编译】之五十六:【QGIS_CORE跨平台编译】—【qgsmeshcalclexer.cpp生成】
  • ar时间序列
  • Android 14 AAOS audio
  • 文心一言 VS 讯飞星火 VS chatgpt (207)-- 算法导论15.4 4题
  • 【论文笔记】Attention Is All You Need
  • (亲测可用)Adobe Photoshop 2024下载与安装
  • uniapp聊天记录本地存储(详细易懂)
  • Vue.js中的$nextTick
  • python+mysql咖啡店推荐系统django+vue
  • 综合实验nginx+nfs+kpa
  • springboot197基于springboot的毕业设计系统的开发
  • group by报错
  • 3、云原生安全之falco的部署
  • Docker架构概述
  • 安装 node 错误的配置环境变量之后使用 npm 报错
  • Matlab 最小二乘插值(曲线拟合)
  • AWTK-MVVM 配置文件模型
  • 【活动】金三银四,前端工程师如何把握求职黄金期
  • 萌新学习RSA第二天(离线分解整数N)
  • STM32学习和实践笔记(1): 装好了的keil μVision 5
  • 企业计算机服务器中了360勒索病毒如何解密,360后缀勒索病毒处理流程
  • 【图像拼接/视频拼接】论文精读:Efficient Video Stitching Based on Fast Structure Deformation
  • LASSO算法