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

Get help with using AutoHotkey and its commands and hotkeys
murataygun
Posts: 31
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: 31
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: 1870
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
GitHub: AAhkUser
Location: France

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

Return to “Ask For Help”

Who is online

Users browsing this forum: Alexjc, Bing [Bot], mikeyww and 30 guests