How to use jsonStringify method in Mocha

Best JavaScript code snippet using mocha

50.JSON.stringify.js

Source:50.JSON.stringify.js Github

copy

Full Screen

...174let obj1 = { a: 'aa' }175let obj2 = { name: '前端胖头鱼', a: obj1, b: obj1 }176obj2.obj = obj2177// console.log(jsonstringify(obj2))178console.log(jsonStringify(BigInt(1)))179// console.log(JSON.stringify(BigInt(1)))180/*181// 1. 转换对象182console.log(JSON.stringify({ name: '前端胖头鱼', sex: 'boy' }))183// 2. 转换普通值184console.log(JSON.stringify('前端胖头鱼'))185console.log(JSON.stringify(1))186console.log(JSON.stringify(true))187console.log(JSON.stringify(null))188// 3. 指定replacer函数189console.log(JSON.stringify({ name: '前端胖头鱼', sex: 'boy', age: 100 }, (key, value) => {190 return typeof value === 'number' ? undefined : value191}))192// 4. 指定数组...

Full Screen

Full Screen

index.js

Source:index.js Github

copy

Full Screen

...14// Date 日期调用了 toJSON() 将其转换为了 string 字符串(同Date.toISOString()),因此会被当做字符串处理。15// NaN 和 Infinity 格式的数值及 null 都会被当做 null。16// 其他类型的对象,包括 Map/Set/WeakMap/WeakSet,仅会序列化可枚举的属性。17const isObject = (obj) => typeof obj === "object" && obj !== null;18function jsonStringify(obj, map = new WeakMap()) {19 // 先判断循环引用20 if (isObject(obj) && map.has(obj)) throw TypeError("cyclic object value");21 isObject(obj) && map.set(obj, true);22 // 判断BigInt23 if (Object.prototype.toString.call(obj) === "[object BigInt]") {24 throw TypeError("Do not know how to serialize a BigInt");25 }26 if (typeof obj === "string") {27 return `"${obj}"`;28 }29 if (obj === Infinity || Number.isNaN(obj) || obj === null) {30 return "null";31 }32 if (33 obj === undefined ||34 typeof obj === "function" ||35 typeof obj === "symbol"36 ) {37 return undefined;38 }39 if (isObject(obj)) {40 if (obj.toJSON && typeof obj.toJSON === "function") {41 return jsonStringify(obj.toJSON(), map);42 } else if (Array.isArray(obj)) {43 let result = [];44 obj.forEach((item, index) => {45 let value = jsonStringify(item, map);46 if (value !== undefined) {47 result.push(value);48 }49 });50 return `[${result}]`;51 } else {52 let result = [];53 Object.keys(obj).forEach((item) => {54 let value = jsonStringify(obj[item], map);55 if (value !== undefined) {56 result.push(`"${item}":${value}`);57 }58 });59 return ("{" + result + "}").replace(/'/g, '"');60 }61 }62 return String(obj);63}64// console.log(JSON.stringify(BigInt(11111)));65// console.log(Object.prototype.toString.call(BigInt(11111)));66// console.log(JSON.stringify(new Date(0)));67// console.log(JSON.stringify(""));68// console.log(JSON.stringify(1));69// console.log(JSON.stringify(false));70// console.log(JSON.stringify(null));71// console.log(JSON.stringify(NaN));72// console.log(JSON.stringify(Infinity));73// console.log(JSON.stringify(undefined));74// console.log(JSON.stringify(function () {}));75// console.log(JSON.stringify(Symbol()));76// console.log(JSON.stringify([1, 2, 3]));77// console.log(78// JSON.stringify({79// b: 1,80// toJSON() {81// return "a";82// },83// })84// );85// console.log(jsonStringify(BigInt(11111)));86// const a = { b: 1 };87// a.c = a;88// console.log(JSON.stringify(a));89// console.log(jsonStringify(a));90// console.log(jsonStringify(new Date(0)));91// console.log(jsonStringify(""));92// console.log(jsonStringify(1));93// console.log(jsonStringify(false));94// console.log(jsonStringify(null));95// console.log(jsonStringify(NaN));96// console.log(jsonStringify(Infinity));97// console.log(jsonStringify(undefined));98// console.log(jsonStringify(function () {}));99// console.log(jsonStringify(Symbol()));100// console.log(jsonStringify([1, 2, 3]));101// console.log(102// jsonStringify({103// b: 1,104// toJSON() {105// return "a";106// },107// })108// );109let nl = null;110console.log(jsonStringify(nl) === JSON.stringify(nl));111// true112let und = undefined;113console.log(jsonStringify(undefined) === JSON.stringify(undefined));114// true115let boo = false;116console.log(jsonStringify(boo) === JSON.stringify(boo));117// true118let nan = NaN;119console.log(jsonStringify(nan) === JSON.stringify(nan));120// true121let inf = Infinity;122console.log(jsonStringify(Infinity) === JSON.stringify(Infinity));123// true124let str = "jack";125console.log(jsonStringify(str) === JSON.stringify(str));126// true127let reg = new RegExp("w");128console.log(jsonStringify(reg) === JSON.stringify(reg));129// true130let date = new Date();131console.log(jsonStringify(date) === JSON.stringify(date));132// true133let sym = Symbol(1);134console.log(jsonStringify(sym) === JSON.stringify(sym));135// true136let array = [1, 2, 3];137console.log(jsonStringify(array) === JSON.stringify(array));138// true139let obj = {140 name: "jack",141 age: 18,142 attr: ["coding", 123],143 date: new Date(0),144 uni: Symbol(2),145 sayHi: function () {146 console.log("hi");147 },148 info: {149 sister: "lily",150 age: 16,151 intro: {152 money: undefined,153 job: null,154 },155 },156};157console.log(jsonStringify(obj) === JSON.stringify(obj));...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

1/*jshint node: true */2/*global describe, it, before */3'use strict';4if (typeof module !== 'undefined' && module.exports) {5 var Should = require('should');6 var JSONStringifyDate = require('../index');7}8describe('JSON stringify date', function () {9 describe('#stringify', function () {10 describe('utc option false', function () {11 before(function () {12 JSONStringifyDate.setOptions({utc: false});13 });14 it('should stringify local date correctly', function () {15 JSONStringifyDate.stringify({a: new Date()}).should.match(/^\{\"a\"\:\"\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}[\+\-]\d{2}\:\d{2}\"\}$/);16 });17 it('should return local date string', function () {18 JSONStringifyDate.stringify(new Date()).should.match(/[\+\-]\d{2}\:\d{2}\"$/);19 });20 });21 describe('utc option true', function () {22 before(function () {23 JSONStringifyDate.setOptions({utc: true});24 });25 it('should stringify UTC date correctly', function () {26 JSONStringifyDate.stringify({a: new Date()}).should.match(/^\{\"a\"\:\"\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z\"\}$/);27 });28 it('should return UTC date string', function () {29 JSONStringifyDate.stringify(new Date()).should.endWith("Z\"");30 });31 });32 });33 describe('#parse', function () {34 it('should parse UTC date string', function () {35 var res = JSONStringifyDate.parse('{"d":"2014-03-04T00:00:00.000Z"}');36 res.should.have.property('d');37 res.d.should.be.instanceof(Date);38 });39 it('should parse local date string', function () {40 var res = JSONStringifyDate.parse('{"d":"2014-03-04T00:00:00.000-03:00"}');41 res.should.have.property('d');42 res.d.should.be.instanceof(Date);43 });44 it('should not parse a 4 digit string', function () {45 var res = JSONStringifyDate.parse('{"d":"2500"}');46 res.should.have.property('d');47 res.d.should.be.instanceof(String);48 });49 });50 describe('#getReviver', function () {51 describe('without customization', function () {52 it('should parse a UTC date string', function () {53 var reviver = JSONStringifyDate.getReviver();54 reviver("d", "2014-03-04T00:00:00.000Z").should.be.instanceof(Date);55 });56 it('should parse local date string', function () {57 var reviver = JSONStringifyDate.getReviver();58 reviver("d", "2014-03-04T00:00:00.000-03:00").should.be.instanceof(Date);59 });60 });61 describe('with customization', function () {62 it('should parse a UTC date string', function () {63 var reviver = JSONStringifyDate.getReviver(function (key, value) { return value.toString(); });64 reviver("d", "2014-03-04T00:00:00.000Z").should.be.instanceof(String);65 });66 it('should parse local date string', function () {67 var reviver = JSONStringifyDate.getReviver(function (key, value) { return value.toString(); });68 reviver("d", "2014-03-04T00:00:00.000-03:00").should.be.instanceof(String);69 });70 it('should be able to customize', function () {71 var reviver = JSONStringifyDate.getReviver(function (key, value) { return 'custom ' + value.getDate(); });72 reviver("d", "2014-03-04T00:00:00.000-03:00").should.match(/custom \d+/);73 });74 });75 });76 describe('#getReplacer', function () {77 describe('UTC option false', function () {78 before(function () {79 JSONStringifyDate.setOptions({utc: false});80 });81 describe('without customization', function () {82 it('should return local date correctly', function () {83 var replacer = JSONStringifyDate.getReplacer();84 replacer('a', new Date()).should.match(/^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}[\+\-]\d{2}\:\d{2}$/);85 });86 });87 describe('with customization', function () {88 it('should return local date correctly', function () {89 var replacer = JSONStringifyDate.getReplacer(function (key, value) {90 return value;91 });92 replacer('a', new Date()).should.match(/^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}[\+\-]\d{2}\:\d{2}$/);93 });94 it('should be able to customize', function () {95 var replacer = JSONStringifyDate.getReplacer(function (key, value) {96 return 'custom ' + value.getDate();97 });98 replacer('a', new Date()).should.match(/custom \d+$/);99 });100 });101 });102 describe('UTC option true', function () {103 before(function () {104 JSONStringifyDate.setOptions({utc: true});105 });106 describe('without customization', function () {107 it('should return UTC date string', function () {108 var replacer = JSONStringifyDate.getReplacer();109 replacer('a', new Date()).should.match(/^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/);110 });111 });112 describe('with customization', function () {113 it('should return local date correctly', function () {114 var replacer = JSONStringifyDate.getReplacer(function (key, value) {115 return value;116 });117 replacer('a', new Date()).should.match(/^\d{4}-\d{2}-\d{2}T\d{2}\:\d{2}\:\d{2}\.\d{3}Z$/);118 });119 it('should be able to customize', function () {120 var replacer = JSONStringifyDate.getReplacer(function (key, value) {121 return 'custom ' + value.getDate();122 });123 replacer('a', new Date()).should.match(/custom \d+$/);124 });125 });126 });127 });...

Full Screen

Full Screen

json-stringify.js

Source:json-stringify.js Github

copy

Full Screen

...18 * 对包含循环引用的对象(对象之间相互引用,形成无限循环)执行此方法,会抛出错误。19 * @param {*} value 20 * @param {*} memory 21 */22function jsonStringify(value, memory) {23 if (typeof value === 'undefined' || typeof value === 'function' || typeof value === 'symbol') {24 return 'undefined';25 }26 if (value === null) {27 return 'null';28 }29 if (typeof value !== 'object' && typeof value !== 'function') {30 if (typeof value !== 'string') {31 return (value).toString();32 }33 return `"${(value).toString()}"`;34 }35 if (!memory) {36 memory = new WeakMap();37 }38 // 发现循环引用报错39 if (memory.has(value)) {40 throw new Error('value has cycled object');41 }42 memory.set(value, true);43 if (typeof value.toJSON === 'function') {44 return value.toJSON();45 }46 let result = [];47 // 数组对象48 if (Array.isArray(value)) {49 value.forEach((_value, index, arr) => {50 result.push(`${jsonStringify(_value, memory)}`);51 });52 return `[${result.join(',')}]`.replace(/'/g, '"');53 }54 // Date对象55 if (Object.prototype.toString.call(value) === '[object Date]') {56 return value.toJSON();57 }58 // Regex对象59 if (Object.prototype.toString.call(value) === '[object RegExp]') {60 return '{}';61 }62 // 内置对象类型使用toString处理63 if (Object.prototype.toString.call(value) !== '[object Object]') {64 if (Object.prototype.toString.call(value) !== '[object String]') {65 return (value).toString();66 }67 return `"${(value).toString()}"`;68 }69 // 普通对象70 for (let key in value) {71 if (Object.prototype.hasOwnProperty.call(value, key)) {72 result.push(`"${key}":${jsonStringify(value[key], memory)}`);73 }74 }75 return `{${result.join(',')}}`.replace(/'/g, '"');76}77function jsonStringify1(obj) {78 let type = typeof obj;79 if (type !== "object" || type === null) {80 if (/string|undefined|function/.test(type)) {81 obj = '"' + obj + '"';82 }83 return String(obj);84 } else {85 let json = [];86 let arr = obj && obj.constructor === Array;87 for (let k in obj) {88 let v = obj[k];89 let type = typeof v;90 if (/string|undefined|function/.test(type)) {91 v = '"' + v + '"';92 } else if (type === "object") {93 v = jsonStringify(v);94 }95 json.push((arr ? "" : '"' + k + '"') + String(v));96 }97 return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}");98 }99}100// console.log(jsonStringify({})); // '{}'101// console.log(jsonStringify(true)); // 'true'102// console.log(jsonStringify("foo")); // '"foo"'103console.log(jsonStringify([1, "false", false])); // '[1,"false",false]'104console.log(jsonStringify({ x: 5 })); // '{"x":5}'105// console.log(jsonStringify({x: 5, y: 6}));106// "{"x":5,"y":6}"107console.log(jsonStringify([new Number(1), new String("false"), new Boolean(false)]));108// '[1,"false",false]'109// TODO 有问题,不符合预期110// console.log(jsonStringify({x: undefined, y: Object, z: Symbol("")}));111// '{}'112// console.log(jsonStringify([undefined, Object, Symbol("")]));113// '[null,null,null]'114// console.log(jsonStringify({[Symbol("foo")]: "foo"}));115// '{}'116// jsonStringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]);117// '{}'118// jsonStringify(119// {[Symbol.for("foo")]: "foo"},120// function (k, v) {121// if (typeof k === "symbol"){122// return "a symbol";123// }124// }125// );126// undefined127// 不可枚举的属性默认会被忽略:128// console.log(jsonStringify(129// Object.create(130// null,131// {132// x: { value: 'x', enumerable: false },133// y: { value: 'y', enumerable: true }134// }135// )136// ));137// "{"y":"y"}"138// 循环引用报错139// const obj = {140// name: "obj"141// };142// obj.newKey = obj;...

Full Screen

Full Screen

prebuild.js

Source:prebuild.js Github

copy

Full Screen

1const amoRefs = {2 input: '/tmpl/controls/input.twig',3 checkbox: '/tmpl/controls/checkbox.twig',4 checkboxDropdown: '/tmpl/controls/checkboxes_dropdown.twig',5 button: '/tmpl/controls/button.twig',6 date: '/tmpl/controls/date_field.twig',7 radio: '/tmpl/controls/radio.twig',8 select: '/tmpl/controls/select.twig',9 suggest: '/tmpl/controls/suggest.twig',10 textarea: '/tmpl/controls/textarea.twig',11};12const elemTemplate = {13 type: 'amo',14 ref: amoRefs.radio,15 label: 'aaa', //optional - wraps settings16 params: [{key: 'name', val: 'radio', disableJSONStringify: false}]17};18function settingsSetUp() {19 return [20 {21 type: 'amo',22 ref: amoRefs.input,23 label: 'ttt',24 params: [{key: 'name', val: 'input'}, {key: 'value', val: 'inputValue', disableJSONStringify: true}]25 },26 {27 type: 'amo',28 ref: amoRefs.checkbox,29 label: 'aaa',30 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]31 },32 {33 type: 'amo',34 ref: amoRefs.checkboxDropdown,35 label: 'иии',36 params: [{37 key: 'items', val: 'dropdownList', disableJSONStringify: true38 }, {39 key: 'name',40 val: 'drop',41 }]42 },43 {44 type: 'amo',45 ref: amoRefs.checkbox,46 label: 'aaa',47 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]48 },49 {50 type: 'amo',51 ref: amoRefs.checkbox,52 label: 'aaa',53 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]54 },55 {56 type: 'amo',57 ref: amoRefs.checkbox,58 label: 'aaa',59 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]60 },61 {62 type: 'amo',63 ref: amoRefs.checkbox,64 label: 'aaa',65 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]66 },67 {68 type: 'amo',69 ref: amoRefs.checkbox,70 label: 'aaa',71 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]72 },73 {74 type: 'amo',75 ref: amoRefs.checkbox,76 label: 'aaa',77 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]78 },79 {80 type: 'amo',81 ref: amoRefs.checkbox,82 label: 'aaa',83 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]84 },85 {86 type: 'amo',87 ref: amoRefs.checkbox,88 label: 'aaa',89 params: [{key: 'name', val: 'checkbox'}, {key: 'checked', val: 'checkboxValue', disableJSONStringify: true}]90 },91 {92 type: 'amo',93 ref: amoRefs.button,94 force: true,95 params: [{key: 'blue', val: true},96 {key: 'text', val: 'Сохранить'},97 {key:'class_name', val: 'styles.saveButton', disableJSONStringify: true}]98 },99 ];100}101function generateSettingsTwig(settings) {102 const fs = require('fs');103 try {104 fs.unlinkSync('./resources/templates/settings.twig');105 // eslint-disable-next-line no-empty106 } catch (e) {107 }108 const prepend = '<div class="{{ styles.settingsWrapper }}">{% if helpRef %}<div class="{{ styles.helpRef }}"><a href="{{ helpRef }}" target="_blank"><img src="{{ icon_link }}/question.svg" alt=""></a></div>{% endif %}';109 fs.appendFileSync('./resources/templates/settings.twig', prepend);110 for (let elem of settings) {111 let prefix;112 let postfix;113 if (elem.label) {114 prefix = '<div class="{{ styles.field }}">' +115 ' <div class="{{ styles.label }}">' +116 ' <span>' + elem.label + '</span>' +117 ' </div>' +118 ' <div class="{{ styles.value }}">';119 postfix = ' </div>\n' +120 ' </div>';121 } else {122 prefix = '<div class="{{ styles.block }}">';123 postfix = '</div>';124 }125 if (elem.type === 'amo') {126 prefix += '{{ widget.render({ ref: \'' + elem.ref + '\' }, {';127 for (let param of elem.params) {128 if(!param.disableJSONStringify){129 prefix += '\n' + param.key + ':' + JSON.stringify(param.val) + ',';130 }else{131 prefix += '\n' + param.key + ':' + param.val + ',';132 }133 }134 prefix += '\n}) }}';135 }136 prefix += postfix;137 fs.appendFileSync('./resources/templates/settings.twig', prefix);138 }139 fs.appendFileSync('./resources/templates/settings.twig', '</div>');140}...

Full Screen

Full Screen

apiRouter.js

Source:apiRouter.js Github

copy

Full Screen

1const express = require('express');2const apiRouter = express.Router();3const bodyparser = require('body-parser');4const fs = require('fs');5//getAll6apiRouter.get('/', async (req, res, next) => {7 try {8 console.log("GET \n");9 fs.readFile('./data.json', (err, data) => {10 if (err) throw err;11 let jsonData = JSON.parse(data);12 res.status(200).json(jsonData);13 });14 } catch (e) {15 console.log(e);16 res.sendStatus(500);17 }18});19//Create via a simple get -> just for easier in web try20apiRouter.get('/create/:title/:description', async (req, res, next) => {21 try {22 fs.readFile('./data.json', (err, data) => {23 if (err) throw err;24 let jsonData = JSON.parse(data);25 //-- to avoid any problems with id, when an article is deleted.26 // old was just articles.length + 127 const jsonLength = jsonData.articles.length;28 console.log(jsonLength);29 const newID = jsonData.articles[jsonLength-1].ID+1;30 jsonData.articles.push({ID: newID, title: req.params.title, description: req.params.description});31 const jsonStringify = JSON.stringify(jsonData);32 fs.writeFile('./data.json', jsonStringify, (err) => {33 if (err) throw err;34 console.log('The file has been saved!');35 });36 res.status(200).json(jsonStringify);37 });38 } catch (e) {39 console.log(e);40 res.sendStatus(500);41 }42});43//Post -> req.body has new article44apiRouter.post('/post', async (req, res, next) => {45 try {46 console.log("POST WITH DATA");47 console.log("TITLE: " + req.body.title);48 console.log("Description: " +req.body.description);49 console.log("\n");50 fs.readFile('./data.json', (err, data) => {51 if (err) throw err;52 let jsonData = JSON.parse(data);53 //-- to avoid any problems with id, when an article is deleted.54 // old was just articles.length + 155 const jsonLength = jsonData.articles.length;56 console.log(jsonLength);57 const newID = jsonData.articles[jsonLength-1].ID+1;58 jsonData.articles.push({ID: newID, title: req.body.title, description: req.body.description});59 const jsonStringify = JSON.stringify(jsonData);60 fs.writeFile('./data.json', jsonStringify, (err) => {61 if (err) throw err;62 console.log('The file has been saved!');63 });64 res.status(200).json(jsonData);65 });66 } catch (e) {67 console.log(e);68 res.sendStatus(500);69 }70});71apiRouter.delete('/delete/:deleteId', async (req, res, next) => {72 try {73 const deleteID = req.params.deleteId;74 console.log("DELETE item with id: " + deleteID);75 fs.readFile('./data.json', (err, data) => {76 if (err) throw err;77 let jsonData = JSON.parse(data);78 //cause delete/splice didnt work79 jsonData.articles = jsonData.articles.filter(item => item.ID != deleteID);80 const jsonStringify = JSON.stringify(jsonData);81 fs.writeFile('./data.json', jsonStringify, (err) => {82 if (err) throw err;83 console.log('The file has been saved!');84 });85 res.status(200).json(jsonStringify);86 });87 } catch (e) {88 console.log(e);89 res.sendStatus(500);90 }91});92apiRouter.patch('/:updateId', async (req, res, next) => {93 try {94 const updateId = req.params.updateId;95 console.log("UPDATE item with id: " + updateId);96 fs.readFile('./data.json', (err, data) => {97 if (err) throw err;98 let jsonData = JSON.parse(data);99 let updateElement = null;100 for(let key in jsonData.articles){101 if(jsonData.articles[key].ID == updateId){102 updateElement = jsonData.articles[key];103 updateElement.title = req.body.title;104 updateElement.description = req.body.description;105 jsonData.articles.splice(key,1,updateElement);106 break;107 }108 }109 const jsonStringify = JSON.stringify(jsonData);110 fs.writeFile('./data.json', jsonStringify, (err) => {111 if (err) throw err;112 console.log('The file has been saved!');113 });114 res.status(200).json(jsonData);115 });116 } catch (e) {117 console.log(e);118 res.sendStatus(500);119 }120});...

Full Screen

Full Screen

demo.js

Source:demo.js Github

copy

Full Screen

1function jsonStringify(data) {2 let type = typeof data;3 if (type !== 'object') {4 let result = data;5 //data 可能是基础数据类型的情况在这里处理6 if (Number.isNaN(data) || data === Infinity) {7 //NaN 和 Infinity 序列化返回 "null"8 result = "null";9 } else if (type === 'function' || type === 'undefined' || type === 'symbol') {10 // 由于 function 序列化返回 undefined,因此和 undefined、symbol 一起处理11 return undefined;12 } else if (type === 'string') {13 result = '"' + data + '"';14 }15 return String(result);16 } else if (type === 'object') {17 if (data === null) {18 return "null" 19 } else if (data.toJSON && typeof data.toJSON === 'function') {20 return jsonStringify(data.toJSON());21 } else if (data instanceof Array) {22 let result = [];23 //如果是数组,那么数组里面的每一项类型又有可能是多样的24 data.forEach((item, index) => {25 if (typeof item === 'undefined' || typeof item === 'function' || typeof item === 'symbol') {26 result[index] = "null";27 } else {28 result[index] = jsonStringify(item);29 }30 });31 result = "[" + result + "]";32 return result.replace(/'/g, '"');33 } else {34 // 处理普通对象35 let result = [];36 Object.keys(data).forEach((item, index) => {37 if (typeof item !== 'symbol') {38 //key 如果是 symbol 对象,忽略39 if (data[item] !== undefined && typeof data[item] !== 'function' && typeof data[item] !== 'symbol') {40 //键值如果是 undefined、function、symbol 为属性值,忽略41 result.push('"' + item + '"' + ":" + jsonStringify(data[item]));42 }43 }44 });45 return ("{" + result + "}").replace(/'/g, '"');46 }47 }48}49let nl = null;50console.log(jsonStringify(nl) === JSON.stringify(nl));51// true52let und = undefined;53console.log(jsonStringify(undefined) === JSON.stringify(undefined));54// true55let boo = false;56console.log(jsonStringify(boo) === JSON.stringify(boo));57// true58let nan = NaN;59console.log(jsonStringify(nan) === JSON.stringify(nan));60// true61let inf = Infinity;62console.log(jsonStringify(Infinity) === JSON.stringify(Infinity));63// true64let str = "jack";65console.log(jsonStringify(str) === JSON.stringify(str));66// true67let reg = new RegExp("\w");68console.log(jsonStringify(reg) === JSON.stringify(reg));69// true70let date = new Date();71console.log(jsonStringify(date) === JSON.stringify(date));72// true73let sym = Symbol(1);74console.log(jsonStringify(sym) === JSON.stringify(sym));75// true76let array = [1, 2, 3];77console.log(jsonStringify(array) === JSON.stringify(array));78// true79let obj = {80 name: 'jack',81 age: 18,82 attr: ['coding', 123],83 date: new Date(),84 uni: Symbol(2),85 sayHi: function () {86 console.log("hi")87 },88 info: {89 sister: 'lily',90 age: 16,91 intro: {92 money: undefined,93 job: null94 }95 }96}97console.log(jsonStringify(obj) === JSON.stringify(obj));...

Full Screen

Full Screen

jsonStringify.js

Source:jsonStringify.js Github

copy

Full Screen

1function jsonStringify(data) {2 if (typeof data !== 'object') {3 if (Number.isNaN(data) || data === Infinity || data === -Infinity) {4 return 'null';5 } else if (typeof data === 'function' || typeof data === 'symbol' || typeof data === 'undefined') {6 return undefined;7 } else if (typeof data === 'string') {8 return '"' + data + '"';9 }10 return String(data);11 } else if (typeof data === 'object') {12 if (data === null) {13 return 'null';14 } else if (data.toJSON && typeof data.toJSON === 'function') {15 return jsonStringify(data.toJSON());16 } else if (Array.isArray(data)) {17 let result = [];18 data.forEach((element, index) => {19 if (typeof element === 'function' || typeof element === 'symbol' || typeof element === 'undefined') {20 result[index] = 'null';21 } else {22 result[index] = jsonStringify(element);23 }24 });25 result = `[${result}]`;26 return result.replace(/'/g, '"');27 } else {28 let result = [];29 Object.keys(data).forEach((key) => {30 if (typeof key !== 'symbol') {31 let value = data[key];32 if (typeof value !== 'symbol' && typeof value !== 'function' && typeof value !== 'undefined') {33 result.push(`"${key}":${jsonStringify(value)}`);34 }35 }36 });37 return ('{' + result + '}').replace(/'/g, '"');38 }39 }40}41let nl = null;42console.log(jsonStringify(nl) === JSON.stringify(nl));43// true44let und = undefined;45console.log(jsonStringify(undefined) === JSON.stringify(undefined));46// true47let boo = false;48console.log(jsonStringify(boo) === JSON.stringify(boo));49// true50let nan = NaN;51console.log(jsonStringify(nan) === JSON.stringify(nan));52// true53let inf = Infinity;54console.log(jsonStringify(Infinity) === JSON.stringify(Infinity));55// true56let str = 'jack';57console.log(jsonStringify(str) === JSON.stringify(str));58// true59let reg = new RegExp('w');60console.log(jsonStringify(reg) === JSON.stringify(reg));61// true62let date = new Date();63console.log(jsonStringify(date) === JSON.stringify(date));64// true65let sym = Symbol(1);66console.log(jsonStringify(sym) === JSON.stringify(sym));67// true68let array = [1, 2, 3, undefined, Symbol(0)];69console.log(jsonStringify(array) === JSON.stringify(array));70// true71let obj = {72 name: 'jack',73 age: 18,74 attr: ['coding', 123],75 date: new Date(),76 uni: Symbol(2),77 sayHi: function () {78 console.log('hi');79 },80 info: {81 sister: 'lily',82 age: 16,83 intro: {84 money: undefined,85 job: null,86 },87 },88};89console.log(jsonStringify(obj) === JSON.stringify(obj));90console.log(jsonStringify(obj));91console.log(JSON.stringify(obj));...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var Mocha = require('mocha');2var mocha = new Mocha();3mocha.addFile('test.js');4mocha.run(function(failures){5 process.on('exit', function () {6 });7});8var Mocha = require('./node_modules/mocha');

Full Screen

Using AI Code Generation

copy

Full Screen

1const mocha = require('mocha');2const assert = require('assert');3const MarioChar = require('../models/mariochar');4describe('Saving records', function(){5 it('Saves a record to the database', function(done){6 var char = new MarioChar({7 });8 char.save().then(function(){9 assert(char.isNew === false);10 done();11 });12 });13});14const mocha = require('mocha');15const assert = require('assert');16const MarioChar = require('../models/mariochar');17describe('Saving records', function(){18 it('Saves a record to the database', function(done){19 var char = new MarioChar({20 });21 char.save().then(function(){22 assert(char.isNew === false);23 done();24 });25 });26 it('Finds one record from the database', function(done){27 MarioChar.findOne({name: 'Mario'}).then(function(result){28 assert(result.name === 'Mario');29 done();30 });31 });32});33const mocha = require('mocha');34const assert = require('assert');35const MarioChar = require('../models/mariochar');36describe('Saving records', function(){37 it('Saves a record to the database', function(done){38 var char = new MarioChar({39 });40 char.save().then(function(){41 assert(char.isNew === false);42 done();43 });44 });45 it('Finds one record from the database', function(done){

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var expect = require('chai').expect;3var mocha = require('mocha');4var jsonStringify = require('../jsonStringify.js');5describe('jsonStringify', function() {6 it('should return a string', function() {7 var obj = {name: 'John', age: 30, city: 'New York'};8 var str = jsonStringify(obj);9 expect(str).to.be.a('string');10 });11 it('should return a stringified object', function() {12 var obj = {name: 'John', age: 30, city: 'New York'};13 var str = jsonStringify(obj);14 expect(str).to.equal('{"name":"John","age":30,"city":"New York"}');15 });16 it('should return a stringified object with null value', function() {17 var obj = {name: 'John', age: 30, city: 'New York', car: null};18 var str = jsonStringify(obj);19 expect(str).to.equal('{"name":"John","age":30,"city":"New York","car":null}');20 });21 it('should return a stringified object with undefined value', function() {22 var obj = {name: 'John', age: 30, city: 'New York', car: undefined};23 var str = jsonStringify(obj);24 expect(str).to.equal('{"name":"John","age":30,"city":"New York"}');25 });26 it('should return a stringified object with boolean values', function() {27 var obj = {name: 'John', age: 30, city: 'New York', isMarried: true};28 var str = jsonStringify(obj);29 expect(str).to.equal('{"name":"John","age":30,"city":"New York","isMarried":true}');30 });31 it('should return a stringified object with array values', function() {32 var obj = {name: 'John', age: 30, city: 'New York', cars: ['BMW', 'Volvo', 'Mini']};33 var str = jsonStringify(obj);34 expect(str).to.equal('{"name":"John","age":30,"city":"New York","cars":["BMW","Volvo","Mini"]}');35 });36 it('should return a stringified object with nested objects', function()

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mocha = require('mocha');3var jsonStringify = mocha.utils.stringify;4function add(a, b) {5 return a + b;6}7describe('Test add function', function() {8 it('should return 3 when passed 1 and 2', function() {9 assert.equal(add(1, 2), 3);10 });11});12var assert = require('assert');13var mocha = require('mocha');14var jsonStringify = mocha.utils.stringify;15function add(a, b) {16 return a + b;17}18describe('Test add function', function() {19 it('should return 3 when passed 1 and 2', function() {20 assert.equal(add(1, 2), 3);21 });22});23var assert = require('assert');24var mocha = require('mocha');25var jsonStringify = mocha.utils.stringify;26function add(a, b) {27 return a + b;28}29describe('Test add function', function() {30 it('should return 3 when passed 1 and 2', function() {31 assert.equal(add(1, 2), 3);32 });33});34var assert = require('assert');35var mocha = require('mocha');36var jsonStringify = mocha.utils.stringify;37function add(a, b) {38 return a + b;39}40describe('Test add function', function() {41 it('should return 3 when passed 1 and 2', function() {42 assert.equal(add(1, 2), 3);43 });44});45var assert = require('assert');46var mocha = require('mocha');47var jsonStringify = mocha.utils.stringify;48function add(a, b) {49 return a + b;50}51describe('Test add function', function() {52 it('should return 3 when passed 1 and 2', function() {53 assert.equal(add(1, 2), 3);54 });

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var json = { name: 'Mocha', test: 'It is working fine' };3assert.equal(JSON.stringify(json), '{"name":"Mocha","test":"It is working fine"}');4assert.notEqual(JSON.stringify(json), '{"name":"Mocha"}');5var assert = require('assert');6var json = { name: 'Mocha', test: 'It is working fine' };7assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });8assert.notDeepEqual(json, { name: 'Mocha' });9var assert = require('assert');10var json = { name: 'Mocha', test: 'It is working fine' };11assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });12assert.notDeepEqual(json, { name: 'Mocha' });13var assert = require('assert');14var json = { name: 'Mocha', test: 'It is working fine' };15assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });16assert.notDeepEqual(json, { name: 'Mocha' });17var assert = require('assert');18var json = { name: 'Mocha', test: 'It is working fine' };19assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });20assert.notDeepEqual(json, { name: 'Mocha' });21var assert = require('assert');22var json = { name: 'Mocha', test: 'It is working fine' };23assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });24assert.notDeepEqual(json, { name: 'Mocha' });25var assert = require('assert');26var json = { name: 'Mocha', test: 'It is working fine' };27assert.deepEqual(json, { name: 'Mocha', test: 'It is working fine' });28assert.notDeepEqual(json, { name: 'Mocha' });

Full Screen

Using AI Code Generation

copy

Full Screen

1var mocha = require('mocha');2var assert = require('assert');3describe('Stringify', function() {4 it('should return the JSON string', function() {5 var obj = {name: 'John', age: 23};6 var str = mocha.utils.stringify(obj);7 assert.equal(str, '{"name":"John","age":23}');8 });9});10 1 passing (8ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1var mocha = require('mocha');2var assert = require('assert');3var jsonStringify = mocha.utils.stringify;4describe('jsonStringify', function() {5 it('should return a string', function() {6 assert.equal('string', typeof jsonStringify(1));7 });8});91 passing (9ms)101 passing (9ms)

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var mocha = require('mocha');3var jsonStringify = require('../app.js').jsonStringify;4describe('jsonStringify', function () {5 it('should return the stringified value of a number', function () {6 assert.equal(jsonStringify(1), '1');7 });8 it('should return the stringified value of a string', function () {9 assert.equal(jsonStringify('string'), '"string"');10 });11 it('should return the stringified value of an array', function () {12 assert.equal(jsonStringify([1, 2, 3]), '[1,2,3]');13 });14 it('should return the stringified value of an object', function () {15 assert.equal(jsonStringify({ a: 1, b: 2 }), '{"a":1,"b":2}');16 });17 it('should return the stringified value of a boolean', function () {18 assert.equal(jsonStringify(true), 'true');19 });20 it('should return the stringified value of null', function () {21 assert.equal(jsonStringify(null), 'null');22 });23 it('should return the stringified value of undefined', function () {24 assert.equal(jsonStringify(undefined), 'undefined');25 });26});27module.exports = {28 jsonStringify: function (value) {29 return JSON.stringify(value);30 }31};

Full Screen

Using AI Code Generation

copy

Full Screen

1var assert = require('assert');2var str = JSON.stringify({a: 1});3assert.equal(str, '{"a":1}');4console.log(str);5console.log('test passed');6var assert = require('assert');7var str = JSON.stringify({a: 1});8assert.equal(str, '{"a":1}');9console.log(str);10console.log('test passed');11var assert = require('assert');12var str = JSON.stringify({a: 1});13assert.equal(str, '{"a":1}');14console.log(str);15console.log('test passed');16var assert = require('assert');17var str = JSON.stringify({a: 1});18assert.equal(str, '{"a":1}');19console.log(str);20console.log('test passed');21var assert = require('assert');22var str = JSON.stringify({a: 1});23assert.equal(str, '{"a":1}');24console.log(str);25console.log('test passed');26var assert = require('assert');27var str = JSON.stringify({a: 1});28assert.equal(str, '{"a":1}');29console.log(str);30console.log('test passed');31var assert = require('assert');32var str = JSON.stringify({a: 1});33assert.equal(str, '{"a":1}');34console.log(str);35console.log('test passed');36var assert = require('assert');37var str = JSON.stringify({a: 1});38assert.equal(str, '{"a":1}');39console.log(str);40console.log('test passed');41var assert = require('assert');42var str = JSON.stringify({a: 1});43assert.equal(str, '{"a":1}');44console.log(str);45console.log('test passed');46var assert = require('assert');

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Mocha automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful