当我使用 AppleScript 获取对象的属性时,会返回一条记录。
tell application "iPhoto"
properties of album 1
end tell
==> {id:6.442450942E+9, url:"", name:"Events", class:album, type:smart album, parent:missing value, children:{}}
如何迭代返回记录的键/值对,以便我不必确切知道记录中的键是什么?
为了澄清这个问题,我需要枚举键和值,因为我想编写一个通用的 AppleScript 例程来将记录和列表转换为 JSON,然后可以由脚本输出。
最佳答案
我知道这是一个旧的 Q 但现在有可能访问键和值(10.9+)。在 10.9 中,您需要使用脚本库来运行此程序,在 10.10 中,您可以直接在脚本编辑器中使用代码:
use framework "Foundation"
set testRecord to {a:"aaa", b:"bbb", c:"ccc"}
set objCDictionary to current application's NSDictionary's dictionaryWithDictionary:testRecord
set allKeys to objCDictionary's allKeys()
repeat with theKey in allKeys
log theKey as text
log (objCDictionary's valueForKey:theKey) as text
end repeat
这不是黑客或解决方法。它只是使用"new"功能从 AppleScript 访问 Objective-C-Objects。
在搜索其他主题的过程中发现了这个问题,忍不住回答了 ;-)
更新以提供 JSON 功能:
当然,我们可以更深入地研究 Foundation 类并使用 NSJSONSerialization 对象:
use framework "Foundation"
set testRecord to {a:"aaa", b:"bbb", c:"ccc"}
set objCDictionary to current application's NSDictionary's dictionaryWithDictionary:testRecord
set {jsonDictionary, anError} to current application's NSJSONSerialization's dataWithJSONObject:objCDictionary options:(current application's NSJSONWritingPrettyPrinted) |error|:(reference)
if jsonDictionary is missing value then
log "An error occured: " & anError as text
else
log (current application's NSString's alloc()'s initWithData:jsonDictionary encoding:(current application's NSUTF8StringEncoding)) as text
end if
玩得开心,迈克尔/汉堡
关于json - 如何在 AppleScript 中枚举记录的键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18062494/