-1

I have a requirement where I get json string from other API, and this string may or may not be a valid JSON string. How do I Check if the JSON String is valid or not, if it's not valid, how can I make it valid ? What I mean to ask is if there are certain characters that need to be escaped and if they are not escaped then we get error while parsing. Do we have any API to make a JSON string valid ?

I got the code to check if a JSON string is valid or not

Javascript

if (/^[\],:{}\s]*$/.test('{section : "ABCDEFGHI"JKLMNOP"}'.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
  console.log('valid');
}else{
    console.log('Not a valid');
}
Duster
  • 41
  • 2
  • 7
  • *"Do we have any API to make a json string valid?"* Not built-in. It seems like you already know how to check whether it's valid or not ([since you got the code from here](http://stackoverflow.com/a/3710506/218196)). So, is *making* it valid your actual question? – Felix Kling Nov 27 '14 at 07:48
  • 1
    possible duplicate of [How to check if a string is a valid JSON string in JavaScript without using Try/Catch](http://stackoverflow.com/questions/3710204/how-to-check-if-a-string-is-a-valid-json-string-in-javascript-without-using-try) – TResponse Nov 27 '14 at 07:48
  • @loanburger Could be possible, but i need a way to make it valid. – Duster Nov 27 '14 at 07:50
  • 1
    Making it valid is not trivial, since there is not always a unique solution. Take `"foo\c"` for example. It's not valid JSON because `\c` is an invalid escape sequence. But did I mean to write `"fooc"` or `"foo\\c"` or maybe even `"foo\nc"` ? Before you think about how to make JSON valid, you have to come up with some rules. Then you can implement your own parser which can handle that. – Felix Kling Nov 27 '14 at 07:54
  • 2
    Then change the title of your question to better reflect what you are asking. – TResponse Nov 27 '14 at 07:55
  • Let's say we have the following JSON: `'foo'`. How would you "make it valid"? –  Nov 27 '14 at 08:20

1 Answers1

0

That is a non trivial problem. It all depends on your definition of "valid" json. You can turn any string into valid json by escaping quote characters and treating it as a string. For example,

{"foo":"bar

can become

{"stringified":"{\"foo\":\"bar"}

and it is completely valid, but it could also become

{"foo":"bar"}

or

{"foo":"barcelona"}

I would suggest taking another look at your domain or providing a specific problem set in the question.

BlinkyTop
  • 1,124
  • 3
  • 14
  • 19