Wednesday, December 3, 2014 / InDesign, Extendscript, DTP

InDesign CC ExtendScript, Save / Read / Parse JSON

InDesign で json データを扱うときに便利なコードのメモ。

save-read-parse-json.jsx

var eachItem = function(myItemList,func){ for(var i=0; i<myItemList.length; i++){ func(myItemList[i]); } };

var save = function( file,text ){
    file.encoding = "UTF-8";
    var handle = file.open("w");
    if( handle ){
        file.write(json);
        file.close();
    }
};

var read = function( file ){
    file.encoding = "UTF-8";
    var handle = file.open("r");
    if( handle ){
        var text = file.read();
        file.close();
        return text;
    }
    return '';
};

var toJsonObject = function( jsonString ){
    return eval('('+jsonString + ');' );
};

//
// replace your unix user name (in case of MacOSX).
//
var HOME_DIR = '/Users/foo';

// 0)
var json = '{"list":["a","b","c"]}';

// 1) save
var file = new File( HOME_DIR+'/1.json' );
save( file,json );

// 2) read
var json2 = read( file );

// 3) covert string to object
var jsonObject = toJsonObject( json2 );

eachItem( jsonObject.list, function(item){
    $.writeln( '- '+item );
} );