Created
July 22, 2020 16:53
-
-
Save nancystodd/117a2dae0b73f2fb25b63f3d16a4d11d to your computer and use it in GitHub Desktop.
Function to check for valid JSON - from https://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try
This file contains 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
function (someString) { | |
// test string is opened with curly brace or machine bracket | |
if (someString.trim().search(/^(\[|\{){1}/) > -1) { | |
try { // it is, so now let's see if its valid JSON | |
var myJson = JSON.parse(someString); | |
// yep, we're working with valid JSON | |
} catch (e) { | |
// nope, we got what we thought was JSON, it isn't; let's handle it. | |
} | |
} else { | |
// nope, we're working with non-json, no need to parse it fully | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment