Json_foreach always executes once, even if the json array is empty

Hello,
I'm using Mp3tag v3.27a under windows 10 and recently observed during testing of a script for the discogs WS api, that the body of a json_foreach loop was executed, although the json array, it was acting on, was empty or even did not exist. AFAIK in other programming languages, for or foreach loops never iterate, if the stop condition is already met from the start on. So this probably is a bug in the WSS language.
An example for such a foreach loop you can find in the following code snippet:

outputto "Companies"
	json_foreach "companies"
		json_select "entity_type_name"
		sayrest
		say ": "
		json_select "name"
		sayrest
		say "; "
	json_foreach_end

If you insert this code in the file "Discogs Release ID.src" e.g. behind line 50 and use as test case https://www.discogs.com/de/release/4567531-Albert-Collins-Robert-Cray-Johnny-Copeland-Showdown you will get a tag COMPANIES, that contains the string ": ; ". This is because the above WS does not contain a section about Companies, but the foreach loop iterates once.
The corresponding debug output it looks like that:

Script-Line    : 54
Command        : json_foreach
Parameter 1    : >companies<

JSON objects   : ><
JSON loops     : >companies: 1/0<

Output         : ><

Line and position:
0
^

This shows that iteration starts at element 1 of an array with size 0.
I know that there is a workaround by surrounding the foreach loop with

json_select_many_count "companies" "name" 1
ifgreater 0
	outputto "Companies"
	json_foreach "companies"
		.......
	json_foreach_end
endif

It would be nice, if this could be fixed, because it would save some lines of code and some run time.

1 Like

I came across the same behavior before (but hadn't reported it yet). From my research on this bug I'm theorizing that, for loops with 0 entries, the WSS parser doesn't know how to proceed, and simply ignores the json_foreach "S" and json_foreach_end lines and runs the rest.

Good job with the bug catching and workaround. :+1: