Skip to main content
dublove
Legend
June 25, 2025
Answered

How to use js to modify the content in a certain json?

  • June 25, 2025
  • 2 replies
  • 1369 views

For example:

There are two files my.json and aa.jsx in the same path.

I have a code in my.json that looks like this:
{
"oldCode": "60068"
}

 

I now want to use var changeCode="10020" in aa.jsx to change the value of oldCode.

How to achieve it?

Thank you very much.

Correct answer m1b

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).

2 replies

Fred.L
Inspiring
June 25, 2025

Hey @dublove 

From what I read, I understand you have a script that is populated by a Json file. So far so good.

The way I'm using them, Json files are settings files that are created/ updated via .jsx files (ie scripts).

 

My question would then be : Is it the case here? Is your json file created by your .jsx script, or is it just reading datas from it? If so, how was the Json file created in the first place?

 

The usual way would be to run the script / locate the edittext  where value needs to be changed / change it / save it.

From there, the json file should be update with the new value so then when you run the script the next time, it would be with the updated value.

 

I'm afraid I can't help more with the little information provided ^^

dublove
dubloveAuthor
Legend
June 25, 2025

Hi  Fred.L

The json is created manually.
I don't really understand it either.

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
June 25, 2025

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).

dublove
dubloveAuthor
Legend
June 25, 2025

Hi m1b.

Thnak you very much.

The script works fine.
You're really, really amazing.
How did you know I needed a random number?

I was about to ask another question:
Random Match.

Fred.L
Inspiring
June 25, 2025

You're really, really amazing.
How did you know I needed a random number?

Well, you just said it!
He knew because he's amazing. What else? ^^