Page 4 of 4

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 27 Nov 2018, 18:03
by swagfag
  1. run DebugVars(dependency dbgp.ahk) or any other debugger to check what ur loaded object looks like and if it even has the keys ure trying to access. it will also indicate if its an array or object
  2. its an ahk thing, see https://autohotkey.com/docs/Concepts.htm#names

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 27 Nov 2018, 22:43
by Tigerlily
Thank you for your reply swagfag,

I am using the code in my last post to access data in a JSON file and transfer it to an excel document.
my code is essentially this:

Code: Select all

FileRead, JSONdata, %WBdir%\URLdata.json

readJSON := JSON.Load(JSONdata) ; load new 
		
Xl.ActiveSheet.Range("B" URLcell).Value := readJSON["audits","uses-webp-images","details","items"]
		
I know that I am correctly accessing the data up until the point where I hit an array of URLs. I just need the correct syntax to complete my code above to be something like this:

Xl.ActiveSheet.Range("B" URLcell).Value := readJSON["audits","uses-webp-images","details","items"[0],"url"]

Below is a snippet from the whole JSON code that I'm trying to access (the three URLs) - the tree view from the object downward to this point looks like this

object > audits > uses-webp-images

and I'm trying to get to here

object > audits > uses-webp-images > details > items > 0 > url

which would return

https://www.merckvaccines.com/INTERSHOP ... tImage.jpg

snippet of code i'm trying to access:

Code: Select all

    "uses-webp-images": {
      "id": "uses-webp-images",
      "title": "Serve images in next-gen formats",
      "description": "Image formats like JPEG 2000, JPEG XR, and WebP often provide better compression than PNG or JPEG, which means faster downloads and less data consumption. [Learn more](https://developers.google.com/web/tools/lighthouse/audits/webp).",
      "score": 0.58,
      "scoreDisplayMode": "numeric",
      "rawValue": 600,
      "displayValue": [
        "Potential savings of %d KB",
        103
      ],
      "warnings": [],
      "details": {
        "type": "opportunity",
        "headings": [
          {
            "key": "url",
            "valueType": "thumbnail",
            "label": ""
          },
          {
            "key": "url",
            "valueType": "url",
            "label": "URL"
          },
          {
            "key": "totalBytes",
            "valueType": "bytes",
            "label": "Original"
          },
          {
            "key": "wastedBytes",
            "valueType": "bytes",
            "label": "Potential Savings"
          }
        ],
        "items": [
          {
            "url": "https://www.merckvaccines.com/INTERSHOP/static/WFS/Merck-MerckVaccines-Site/-/Merck-MerckVaccines-merckvaccines-responsive/-/img/pneumovax/bannerpatentImage.jpg",
            "fromProtocol": true,
            "isCrossOrigin": false,
            "totalBytes": 65675,
            "wastedBytes": 52827
          },
          {
            "url": "https://www.merckvaccines.com/INTERSHOP/static/WFS/Merck-MerckVaccines-Site/-/-/en_US/img/pneumovax/bannerLeftBgMobile.png",
            "fromProtocol": true,
            "isCrossOrigin": false,
            "totalBytes": 45569,
            "wastedBytes": 44539
          },
          {
            "url": "https://www.merckvaccines.com/INTERSHOP/static/WFS/Merck-MerckVaccines-Site/-/-/en_US/img/merck_logo_mob.png",
            "fromProtocol": true,
            "isCrossOrigin": false,
            "totalBytes": 14760,
            "wastedBytes": 8414
          }
        ],
        "overallSavingsMs": 600,
        "overallSavingsBytes": 105780
      }
    },
Here is a link to the complete JSON file code for reference:

https://docs.google.com/document/d/1o2T ... sp=sharing

THank you so much for your insight and help in advance. Swagfag, I couldn't figure out how to get what I need based on the info you provided, but still very appreciative!

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 28 Nov 2018, 05:54
by Tigerlily
After 6 hours of trying a bunch of stupid things... and reading a ton of JSON, javascript, and AHK docs and forums.. hah

this is the answer I was looking for

what I needed instead of

Code: Select all

Xl.ActiveSheet.Range("B" URLcell).Value := readJSON["audits","uses-webp-images","details","items"[0],"url"]
was

Code: Select all

Xl.ActiveSheet.Range("B" URLcell).Value := readJSON["audits","uses-webp-images","details","items",1,"url"]
the 1 is inserted WITHOUT the quotations... I could have sworn I tried that already, but possibly was accessing the wrong JSON file. the 1 is inserted instead of 0 I'm guessing because Coco wanted to build the option of using A_Index to loop through arrays easily (instead of using (A_Index - 1)).

although I like this syntax better:

Code: Select all

Xl.ActiveSheet.Range("B" URLcell).Value := readJSON.audits.uses-webp-images.details.items.1.url
unfortunately AHK wont read uses-webp-images as a variable. I'm wondering if Coco built a workaround for that other than the different syntax. Or if the different syntax is the workaround? On a general scope in AHK, is there a workaround way to bypass that? Thanks again Coco!

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 28 Nov 2018, 09:50
by swagfag
readJSON.audits["uses-webp-images"].details.items[1].url is the closest ure gonna get
array subscript is the workaround. he couldve made it so it gets converted to snake-case, but why tho? added complexity for something thats already been taken care of.
I'm guessing because Coco wanted to build the option of using A_Index to loop through arrays easily (instead of using (A_Index - 1)).
arrays in AHK are 1 based, so if the function is to return an AHK compatible array, it had better be 1 based

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 28 Nov 2018, 12:20
by Tigerlily
Oh nice, I didn't know you could combine them. I like that much better than typing out all the "," in between (: thanks.

I've been accessing the array in this way to pop them out into an active excel file, but I feel like there is a much better way..

Code: Select all

	!z::
	{
	FileRead, JSONdata, C:\users\user0\URLscores.json

	readJSON := Jxon_Load(JSONdata) ; load new 

		Loop,
		{
		Xl := ComObjActive("Excel.Application") ; creates Excel handle

		Xl.ActiveCell.Value := readJSON["audits","uses-optimized-images","details","items", A_Index ,"url"]

		Worked := readJSON["audits","uses-optimized-images","details","items", A_Index ,"url"]

			if Worked =
					{		
					break
					}
						else
							{
							Xl.ActiveCell.Offset(1,0).Select  ; (row,column), this moves cell 1 down
							}
			}
	}
	return 
I'm just starting to understand how to loop through arrays and what arrays are.

I was trying to pass the parsing command variable through via an InputBox, that way I could access it without re-running the script with an updated code, however it only comes out as a text string maybe a pre-defined dropdown menu would be an easier pass. Is this kind of a variable able to be passed through an InputBox using some sort of Deref() magic?

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 28 Nov 2018, 15:21
by swagfag
parsing command variable
got no clue what u mean by this. this maybe?

Code: Select all

#Include Jxon.ahk
JSONdata =
(LTrim
    {
        "audits": {
            "uses-optimized-images": {
                "details": {
                    "items": [
                        {"url": "helloworld"}
                    ]                   
                }
            }
        }
    }
)

; FileRead, JSONdata, C:\users\user0\URLscores.json
readJSON := Jxon_Load(JSONdata) ; load new 

parsing_cmd_var := "audits.uses-optimized-images.details.items[1].url"
parsing_cmd_var := RegExReplace(parsing_cmd_var, "\[(\d+)\]", ".$1")
; or
; parsing_cmd_var := "audits.uses-optimized-images.details.items.1.url"

Params := StrSplit(parsing_cmd_var, ".")
var := readJSON[Params.RemoveAt(1)]
for each, param in Params
    var := var[param]
MsgBox % var
on a side note, id suggest starting a new thread, since this has little to do with this lib or json in and of itself

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 02 Mar 2020, 05:18
by Delta Pythagorean
Ok, this is probably a better place to put this than "Ask For Help" I guess.

I'm having this strange problem where It's not allowing to read arrays as the base of the whole object.
Here's what I mean:

Code: Select all

[
	["TestVar", "SomeItem", "Variables"],
	["George", "Billy Joe", "Bob", "Sam"],
	["Interactions", "SomeValue", "Yay"]
]
The problem is that JSON.Load() sees the beginning string of the array and freaks out about it saying "Extra Data" when it's a valid array.
If anyone knows why this happens/how to fix it please let me know, not urgent, but "ASAP" would be the preferable word to describe my patience.

EDIT:
To help any further with the problem, putting the string into an object into the script itself runs just fine.

Code: Select all

Array :=
(LTrim Join
	[
		["TestVar", "SomeItem", "Variables"],
		["George", "Billy Joe", "Bob", "Sam"],
		["Interactions", "SomeValue", "Yay"]
	]
)
MsgBox, % Array[1, 1]	; Should output to "TestVar" without quotes.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 02 Mar 2020, 12:27
by freakkk
@Delta Pythagorean

Without seeing any more code where you're getting the error from, I have a hunch it could possibly be an issue with a continuation section you are using??

This is testing out okay for me:

Code: Select all

Array :=  ; <-- continuation section is evaluating an expression
(LTrim Join
	[
		["TestVar", "SomeItem", "Variables"],
		["George", "Billy Joe", "Bob", "Sam"],
		["Interactions", "SomeValue", "Yay"]
	]
)
MsgBox, % Array[1, 1]	; Should output to "TestVar" without quotes.


Array =  ; <-- continuation section is simply a string
(LTrim Join
	[
		["TestVar", "SomeItem", "Variables"],
		["George", "Billy Joe", "Bob", "Sam"],
		["Interactions", "SomeValue", "Yay"]
	]
)
Array := JSON.Load(Array)
MsgBox, % Array[1, 1]	; Should output to "TestVar" without quotes.
I've been working with JSON a lot lately, and any time I get any weird confusion, I usually try creating my object the way I want it in ahk, then writing the results of JSON.Dump(obj) to a file, for examination. Your object seems okay though.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 02 Mar 2020, 14:37
by burque505
First, @freakkk , if I've neglected to say it before thanks for this. Here's what I came up with that I think proves your continuation section theory about @Delta Pythagorean's code , and I've added an #Include for obj2str.ahk for another way to look at the object. If this adds nothing useful, my apologies in advance.

Code: Select all

#Include JSON.ahk
#Include JsonFile.ahk
#Include obj2str.ahk

Array := [["TestVar", "SomeItem", "Variables"],["George", "Billy Joe", "Bob", "Sam"],["Interactions", "SomeValue", "Yay"]]
MsgBox, % Array[2,4] ; should write 'Sam'

Array :=  ; <-- continuation section is evaluating an expression
(LTrim Join
	[
		["TestVar", "SomeItem", "Variables"],
		["George", "Billy Joe", "Bob", "Sam"],
		["Interactions", "SomeValue", "Yay"]
	]
)
MsgBox, % Array[1, 1]	; Should output to "TestVar" without quotes.


Array =  ; <-- continuation section is simply a string
(LTrim Join
	[
		["TestVar", "SomeItem", "Variables"],
		["George", "Billy Joe", "Bob", "Sam"],
		["Interactions", "SomeValue", "Yay"]
	]
)
Array := JSON.Load(Array)
MsgBox, % Array[1, 3]	; Should output to "Variables" without quotes.
MsgBox, % Array[2, 2]	; Should output to "Billy Joe" without quotes.

arrgh := Obj2Str(Array)
MsgBox, %arrgh%

arrghX2 := JSON.Dump(Array)
MsgBox, %arrghX2%
Regards,
burque505

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 05 Mar 2020, 13:11
by Delta Pythagorean
So, I found out that there might be a bug with AHK itself. Currently using the latest version (1.1.32.00) and the static variables in the JSON.Load Call method don't set the variables to any values, making the values of the variables blank.
Here's what I mean:

Code: Select all

Static quot := Chr(34)
MsgBox, quot ; Should return double quote, but instead gives nothing.
I'll have to test whether this is a bug or not. But it seems like a bug to me. If I can confirm this, I'll send a report.
I have no idea what could cause this though.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 05 Mar 2020, 13:30
by boiler
The code you showed shouldn't have been blank. It should have showed quot in the MsgBox. Try it with:

Code: Select all

MsgBox, % quot

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 05 Mar 2020, 13:46
by burque505
This works for me on Win7 SP1 64-bit. Function used because of declaration of 'quot' as 'Static'.

Code: Select all

DoIt()

DoIt() {
Static quot := Chr(34) 
MsgBox, quot ; 'quot'
Msgbox, %quot% ; '"'
}

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 05 Mar 2020, 20:28
by Delta Pythagorean
Minor typo, forgot the Percent sign.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 23 Mar 2020, 16:39
by Delta Pythagorean
I found the problem and why the static variables are not being set.
I was initially executing my code from a static variable before calling the JSON library, here's what I mean:

Code: Select all

Code() {
	Static Init := Code() ; Run this function on startup.

	Str := ; --
	Arr := JSON.Load(Str)
	Return
}
Because I was running the JSON library before the library's Static variables were set, it caused it to malfunction and not give the results I needed.
To fix this I just moved the Code() call to a different section of the script.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 07 May 2020, 21:59
by starionx
I'm new to Json, so I copied Json.ahk from github, but when I run this example I get the following error -

Error 1.jpg
Error 1.jpg (11.94 KiB) Viewed 3109 times

Any ideas?

edit - I'm running ahk version 1.1.14.02, if it makes any difference.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 07 May 2020, 23:19
by swagfag
it does

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 08 May 2020, 00:06
by starionx
:oops: :oops: :oops:

I guess after 6 years, it was time to update.

Re: JSON 2.0 (and Jxon) - JSON lib for AutoHotkey

Posted: 20 Mar 2024, 11:34
by JoeWinograd
Hi Folks,
I thought it would be better to post a separate question for a usage issue, but after three days and more than 30 views, it has received no replies, so I decided to come here and hope that the JSON/Jxon experts hanging here can help.

The quick summary is: How to access JSON elements that are in an array, i.e., enclosed in square brackets? More details at the question thread here: viewtopic.php?f=76&t=127447

Thanks very much! Regards, Joe