'Extendscript in Indesign not creating or writing to file

I am writing a script for Indesign that collects the contents from TextStyleRange objects, adds them to a javascript object, and should then write out a JSON file with the stringified JSON.

I can create the JSON just fine, with the contents from all of the TextStyleRanges in the current document, however the final file never gets written.

Here is a simplified example of what I have:

#include "json2.js";
main();
function main(){
    myObj = { "key_1": "value_1", "key_2": "value_2" };
    myContents = JSON.stringify(myObj, null, 4);
    myFile = new File("~/Documents/myproject/en/translation.json");
    myFile.open("w");
    myFile.write( myContents );
    $.writeln( myContents );
    myFile.close();
}

In the VSCode debugger I can correctly see the JSON being output by $.writeln, however the file is not being created on disk. Any ideas what might be going wrong?

I'm using Windows 10, and Adobe Indesign 2022.

I have also tried with file edit but no luck:

myFile.open("e", "????", "????");


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source