InDesign で json データを扱うときに便利なコードのメモ。
このコードを含めて、たびたび使いそうな ExtendScript コードをまとめたレポジトリはこちら: https://github.com/mindboard/indesign-extendscript
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 Mac OS X).
//
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 );
} );