Page 1 of 1

Test that JSON received is valid

Posted: Fri May 18, 2018 5:15 am
by KimD
I'm working on an app that reads JSON from a web service. For this I'm using JSONImport, putting the JSON into a LC array and from the array into an SQLite db. It seems to work nicely. Then I thought "I really should code this so that it doesn't explode if the web service passes it invalid JSON". So to see what would happen if the app received invalid JSON I:
- wrote the working JSON that I received from the web service into a file; then
- chopped the final "}" off the JSON (to make it incorrect); then
- had JSONImport read the file containing the incorrect JSON.

The IDE stops dead with an "LCB Error in file json.lcb at line 65: syntax error: 1:2734 unexpected end of input" error.

Is there an easy way for me to test that JSON is valid before I pass it to JSONImport?

Ultimately my app will need to run on Windows desktop + Android + IOS. I've seen a few forum posts about an IsJSON function in a fastJSON library. Is that the way to go? I was hoping to be able to keep using JSONImport as it seems to do the job fine when it does receive valid JSON.

Thanks in advance

Kim

LC9 on Windows 10

Re: Test that JSON received is valid

Posted: Fri May 18, 2018 1:37 pm
by dunbarx
Not specific to your import, would using the "try/catch" structure do the trick?

Craig

Re: Test that JSON received is valid

Posted: Fri May 18, 2018 3:00 pm
by MaxV
Just use regex, this is the code in Javascript:

Code: Select all

 var my_JSON_object = !(/[^,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]/.test(
             text.replace(/"(\\.|[^"\\])*"/g, ''))) &&
         eval('(' + text + ')');

Re: Test that JSON received is valid

Posted: Fri May 18, 2018 4:21 pm
by jacque
I've used try!/catch around a JSONImport function and it works. No need for regex that way.

Re: Test that JSON received is valid

Posted: Fri May 18, 2018 9:40 pm
by KimD
Thanks Craig, Max & Jacque. I will give try / catch a go. So much to learn............