Use Javascript for automation (JXA) to create a pl

2019-06-13 19:47发布

I'm looking into creating a JXA to build a plist. My starting point is an AppleScript that I found here. I came up with this snippet:

var se = Application('System Events');

var item1 = se.PropertyListItem({kind: "string", name: "employee_name", value: employeeName}).make();

var plistFile = se.PropertyListFile({name: '/Users/armando/Desktop/x.plist', PropertyListItem: [item1]}).make();

ScriptEditor compiles without errors, the file got created but no entries are produced on the file. I guess I'm missing something on how to populate the PropertyListFile property where the actual entries are handled.

Any clue about how to correctly use JXA with System Event's plist?

(in case you wonder why not use the AppleScript approach is because I'm pulling the data from Excel through automation but need to validate data type consistency and nulls... javascript seemed to me a more straight forward approach to look into variable types and make corrections as needed)

2条回答
再贱就再见
2楼-- · 2019-06-13 20:14

Creating property list files with System Events is very tedious.
With JXA you can use Objective-C code directly.

var employeeName = "John Doe";

var item1 = { "employee_name" : employeeName };
var plist = $.NSDictionary.dictionaryWithDictionary(item1);
plist.writeToFileAtomically( '/Users/armando/Desktop/x.plist', true);
查看更多
欢心
3楼-- · 2019-06-13 20:19

Tested around because I thought that it MUST be possible to solve the problem using JXA and found this solution. It looks quite simple but it really took some time to find :-/

// Setting some variables
plist_path = "~/Desktop/example.plist"
employeeName = "Michael"

// Storing the Application object
se = Application('System Events')

// Create PropertyListItems
propertyListItem1 = se.PropertyListItem({
    kind: "string", 
    name: "employee_name", 
    value: employeeName
});

// Create the PropertyListFile
plistFile = se.PropertyListFile({
    name: plist_path
}).make()

// Push the PropertyListItem to the PropertyListFile
plistFile.propertyListItems.push(propertyListItem1)

Enjoy, Michael / Hamburg

查看更多
登录 后发表回答