I'm working on an app where a function needs to validate if a provided string parameter is valid json. But the function also needs to handle JSON which has been copied from jira. For example, the json could look like this:
"{
"query": {
"size": 0,
"aggregations": {
"ipTag": {
"terms": {
"field": "ipTag",
"size": 1001
}
}
}
},
"table": "ip_info_table"
}"
Not sure if the following format of the string param is becuase it was copied/pasted from Jira, or if it has to do with MUI Input controls. But anyway, this is what the format looks like when I copy/paste the variable into a CDT watch:
"{\n \"query\": {\n \"size\": 0,\n ...."
So what kind of code routine would you recommend to handle this scenario? Is there some logic that I can use to format the sample input parameter value above, so that JSON.parse() will properly validate the param value as JSON?
I would use JSON.parse
to validate JSON:
let valid = false;
try {
JSON.parse(str);
console.log('valid');
valid = true;
} catch {
console.log('invalid');
}
console.log(valid);
Examples:
const json = `{
"query": {
"size": 0,
"aggregations": {
"ipTag": {
"terms": {
"field": "ipTag",
"size": 1001
}
}
}
},
"table": "ip_info_table"
}`;
try {
JSON.parse(json);
console.log('valid');
} catch {
console.log('invalid');
}
const json = "{\n \"query\": {\n \"size\": 0\n} }";
try {
JSON.parse(json);
console.log('valid');
} catch {
console.log('invalid');
}
const json = `{
"query": {
"size": 0,
"aggregations": {
"ipTag": {
"terms": {
"field": "ipTag",
"size": 1001
}
}
}
},
"table": "ip_info_table",
}`;
try {
JSON.parse(json);
console.log('valid');
} catch {
console.log('invalid');
}