'what is a reliable way to validate if this string is valid json?
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 ...."
- JSON.parse(param) throws error
- JSON.parse(JSON.stringify(param)) return success
- But JSON.parse(JSON.stringify('junk')) also returns success although a single word of junk is not considered valid json
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?
Solution 1:[1]
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');
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jabaa |
