I have CLI app where user provide a JSON. I need to check if JSON is valid. I found somehting like this may work great:
function isJsonValid(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
But while I debug my app i noticed that there is a little problem that all " and ' and spaces from command are stripped.
so json as:
{
"key1": "value1",
"key2": "value2"
}
is changed to something as:
{key1:value1,key2:value2}
I need a regex which will check if this stripped JSON is valid somehow.
So result should looks like:
re.test({key1:value1,key2:value2}) // true
re.test({key1:value1}) // true
re.test({key1:value1,}) // false, extra comma
re.test({key1:value1, key2}) // false, missing value of key2
re.test({key1:value1, key2:value2) // false, missing closing }
re.test({key1:value1, key2:value2}}) // false, extra closing }
Can someone please help me with regex part? This is unfortunately really not my strong side.
key:valuepairs, or do you have to allow for nested objects and/or arrays?{- opening bracket,key+:+value+ closing bracket}Whilekey:valuepart can repeat multiple time and should be seperate with commatrue, the passed JSON is valid, if it returnsfalsean error has occurred, and the JSON is not valid. Why to bother to re-check?JSONinstead of evaluate the stripped version, There's definitely something wrong there.. Can you tell us how is thatstrvariable passed toisJsonValidfunction? -- @Teemu, The function always return false becausestris notJSON