使用Javascript进行自动化(JXA)来创建plist

时间:2015-07-23 06:01:35

标签: javascript macos automation javascript-automation jxa

我正在考虑创建一个JXA来构建一个plist。我的出发点是AppleScript,我发现here。我想出了这个片段:

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编译没有错误,文件已创建,但文件上没有生成任何条目。我想我在如何填充处理实际条目的PropertyListFile属性时遗漏了一些东西。

有关如何正确使用JXA与系统事件的plist的任何线索?

(如果你想知道为什么不使用AppleScript方法是因为我通过自动化从Excel中提取数据但需要验证数据类型的一致性和空值... javascript对我来说似乎更直接的方法查看变量类型并根据需要进行更正)

2 个答案:

答案 0 :(得分:2)

使用系统事件创建属性列表文件非常繁琐 使用JXA,您可以直接使用Objective-C代码。

var employeeName = "John Doe";

var item1 = { "employee_name" : employeeName };
var plist = $.NSDictionary.dictionaryWithDictionary(item1);
plist.writeToFileAtomically( '/Users/armando/Desktop/x.plist', true);

答案 1 :(得分:1)

测试周围是因为我认为必须有可能使用JXA解决问题并找到此解决方案。它看起来很简单,但确实需要一些时间才能找到: - /

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

享受,迈克尔/汉堡