Check if JSON string is a valid Json object. Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
murataygun
Posts: 104
Joined: 07 Aug 2015, 15:53

Check if JSON string is a valid Json object.

20 Sep 2020, 11:52

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.
murataygun
Posts: 104
Joined: 07 Aug 2015, 15:53

Re: Check if JSON string is a valid Json object.

20 Sep 2020, 12:05

mikeyww wrote:
20 Sep 2020, 11:55
RegExReplace
Thank you very much. Bu I'm asking if anyone already done some sort of function. You see Its too complicated.
teadrinker
Posts: 4331
Joined: 29 Mar 2015, 09:41
Contact:

Re: Check if JSON string is a valid Json object.

20 Sep 2020, 13:47

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
}
A_AhkUser
Posts: 1147
Joined: 06 Mar 2017, 16:18
Location: France
Contact:

Re: Check if JSON string is a valid Json object.  Topic is solved

20 Sep 2020, 15:42

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
my scripts
murataygun
Posts: 104
Joined: 07 Aug 2015, 15:53

Re: Check if JSON string is a valid Json object.

02 Dec 2020, 17:51

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.

Return to “Ask for Help (v1)”

Who is online

Users browsing this forum: mikeyww, Thorlian and 283 guests