Page 1 of 1
Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 11:52
by murataygun
I've searched all AHK forums but found nothing. I just want to check a fetched string data is a validly formatted Json string. I need something like this;
It checks if json is valid. But in Javascript.
Code: Select all
if (/^[\],:{}\s]*$/.test(text.replace(/\\["\\\/bfnrtu]/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, ''))) {
//the json is ok
}else{
//the json is not ok
}
In AHK?
Thank you.
Re: Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 11:55
by mikeyww
Re: Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 12:05
by murataygun
Thank you very much. Bu I'm asking if anyone already done some sort of function. You see Its too complicated.
Re: Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 13:47
by teadrinker
You can use javascript from AHK:
Code: Select all
json = {"key":"value"}
MsgBox, % IsJsonValid(json)
json = {"key":"value}
MsgBox, % IsJsonValid(json)
IsJsonValid(json) {
JS := GetJS()
try JS.("JSON.stringify(" . json . ")")
catch
Return false
Return true
}
GetJS() {
static doc := ComObjCreate("htmlfile")
, __ := doc.write("<meta http-equiv=""X-UA-Compatible"" content=""IE=9"">")
, JS := ObjBindMethod(doc.parentWindow, "eval")
Return JS
}
Re: Check if JSON string is a valid Json object. Topic is solved
Posted: 20 Sep 2020, 15:42
by A_AhkUser
without using eval:
Code: Select all
json = {"key":"value"}
MsgBox, % IsJsonValid(json)
json = {"key":"value}
MsgBox, % IsJsonValid(json)
isJsonValid(string) {
static doc := ComObjCreate("htmlfile")
, __ := doc.write("<meta http-equiv=""X-UA-Compatible"" content=""IE=9"">")
, parse := ObjBindMethod(doc.parentWindow.JSON, "parse")
try %parse%(string)
catch
return false
return true
}
return
A_AhkUser
Re: Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 15:52
by teadrinker
Nice!
Re: Check if JSON string is a valid Json object.
Posted: 20 Sep 2020, 16:52
by murataygun
Thank you very much coders
Re: Check if JSON string is a valid Json object.
Posted: 02 Dec 2020, 17:51
by murataygun
Update:
This answers is working fine on Windows 7 with SP1 and Windows 10 but Not Windows7 without SP1 (yes we have too old PCs and stuff doesnt touch if it works). I must support that machines. And my search is on again.
Re: Check if JSON string is a valid Json object.
Posted: 02 Dec 2020, 17:59
by teadrinker
Do any error messages appear?