Last active
February 1, 2020 00:12
-
-
Save psenger/324fc57b51c51be3203f89842d82973b to your computer and use it in GitHub Desktop.
[IsJson hasJsonStructure safeJsonParse test] #JavaScript #TestHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * https://stackoverflow.com/questions/9804777/how-to-test-if-a-string-is-json-or-not | |
| */ | |
| const isJson = function isJson(item) { | |
| if ( Array.isArray(item)) return false; | |
| if ( Buffer.isBuffer(item)) return false; | |
| // by doing this, JSON.parse(1234) or JSON.parse(0) or JSON.parse(false) or JSON.parse(null) are invalid. | |
| item = typeof item !== 'string' ? JSON.stringify(item) : item; | |
| try { | |
| item = JSON.parse(item); | |
| } catch (e) { | |
| return false; | |
| } | |
| return (typeof item === 'object' && item !== null); | |
| }; | |
| const hasJsonStructure = function hasJsonStructure(str) { | |
| if (typeof str !== 'string') return false; | |
| try { | |
| const result = JSON.parse(str); | |
| return Object.prototype.toString.call(result) === '[object Object]' | |
| || Array.isArray(result); | |
| } catch (err) { | |
| return false; | |
| } | |
| }; | |
| const safeJsonParse = function safeJsonParse(str) { | |
| try { | |
| return [null, JSON.parse(str)]; | |
| } catch (err) { | |
| return [err]; | |
| } | |
| }; | |
| [ | |
| null, | |
| undefined, | |
| true, | |
| false, | |
| 1, | |
| -7, | |
| 5.5, | |
| -46.23, | |
| '', | |
| 'this is a test', | |
| [], | |
| [1,2,3,4], | |
| ['a','b','c'], | |
| new Array(), | |
| new Array(10), | |
| new Array([1,2,3,4]), | |
| new Array(['a','b','c']), | |
| new Buffer(3), | |
| new Buffer('this is a test', 'utf8'), | |
| new Number(), | |
| new Number(1), | |
| new Number(-7), | |
| new Number(5.5), | |
| new Number(-46.23), | |
| ].forEach(subject=>console.log(`isJson(${subject})=${isJson(subject)}`)); | |
| [ | |
| '', | |
| ' ', | |
| JSON.stringify({a:'1',b:['a','b','c']}), | |
| JSON.stringify(['a','b','c']), | |
| JSON.stringify([1,2,3,4]), | |
| ].forEach(subject=>console.log(`isJson(${subject})=${isJson(subject)}`)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment