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
Test that JSON received is valid
Moderators: FourthWorld, heatherlaine, Klaus, kevinmiller
-
- VIP Livecode Opensource Backer
- Posts: 9660
- Joined: Wed May 06, 2009 2:28 pm
- Location: New York, NY
Re: Test that JSON received is valid
Not specific to your import, would using the "try/catch" structure do the trick?
Craig
Craig
Re: Test that JSON received is valid
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 + ')');
Livecode Wiki: http://livecode.wikia.com
My blog: https://livecode-blogger.blogspot.com
To post code use this: http://tinyurl.com/ogp6d5w
My blog: https://livecode-blogger.blogspot.com
To post code use this: http://tinyurl.com/ogp6d5w
-
- VIP Livecode Opensource Backer
- Posts: 7233
- Joined: Sat Apr 08, 2006 8:31 pm
- Location: Minneapolis MN
- Contact:
Re: Test that JSON received is valid
I've used try!/catch around a JSONImport function and it works. No need for regex that way.
Jacqueline Landman Gay | jacque at hyperactivesw dot com
HyperActive Software | http://www.hyperactivesw.com
HyperActive Software | http://www.hyperactivesw.com
Re: Test that JSON received is valid
Thanks Craig, Max & Jacque. I will give try / catch a go. So much to learn............