Hi @dublove have a study of this:
/**
* Example of reading, parse and writing JSON file.
*
* @author m1b
* @version 2025-06-25
* @discussion https://community.adobe.com/t5/indesign-discussions/how-to-use-js-to-modify-the-content-in-a-certain-json/m-p/15387727
*/
//@include '../../../../Lib/json3.js'
(function () {
// read the json file's contents
var myJSON = readFile('my.json');
if (!myJSON)
return alert('Could not read JSON file.');
// parse as json
myJSON = JSON.parse(myJSON);
alert('oldCode = ' + myJSON.oldCode);
// change the json
myJSON.oldCode = Math.floor(Math.random() * 999999);
// write the json file
var f = writeFile('my.json', JSON.stringify(myJSON, undefined, '\t'));
})();
/**
* Read a file and return contents.
* Will ask for file if no path is supplied.
* @author m1b
* @version 2023-08-17
* @param {File|CSFile|String} [file] - file or path.
* @param {String} [fileExtension] - the file extension (default: '').
* @param {Number} [lineCount] - the number of lines to read (default: all).
* @returns {String} file contents.
*/
function readFile(file, fileExtension, lineCount) {
fileExtension = (fileExtension || '').replace('.', '');
lineCount = lineCount || 0;
var f,
data = '';
if (file != undefined) {
if (file.constructor.name == 'String') {
if (file.indexOf('/') < 0)
file = File($.fileName).parent + '/' + file;
f = File(file);
}
else if (file.constructor.name == 'File')
f = file;
}
if (
f == undefined
|| typeof f.open !== 'function'
)
f = Utility.chooseFile(fileExtension, false, file);
if (!f || !f.exists)
return;
$.appEncoding = 'UTF-8';
f.open('r');
if (lineCount == 0)
// read whole file
data = f.read();
else
// read first line(s)
while (lineCount--)
data += f.readln() + '\n';
f.close();
if (data == undefined)
throw Error('readFile: Could not read data.');
return data;
};
/**
* Write text to file.
* @author m1b
* @version 2023-05-30
* @param {File|String} file - the file|path to write to.
* @param {String} data - the data to write.
* @param {Boolean} append - whether to append to end of file (default: false).
* @returns {File} the written file
*/
function writeFile(file, data, append) {
var success,
writeMode = append == true ? 'a' : 'w',
bom = "\uFEFF";
if (file.constructor.name == 'String') {
if (file.indexOf('/') < 0)
file = File($.fileName).parent + '/' + file;
file = File(file);
}
try {
file.open(writeMode);
file.encoding = "UTF-8";
success = file.write(bom + data);
file.close();
}
catch (error) {
success = false;
alert('writeFile failed: ' + error.message);
}
if (success)
return file;
};
Note: this script uses the json3.js library. It won't work without it (or a similar library).