Bry*_*yle 3 applescript json applescript-objc
当我使用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:{}}
Run Code Online (Sandbox Code Playgroud)
如何迭代返回记录的键/值对,以便我不必确切地知道记录中的键是什么?
为了澄清这个问题,我需要枚举键和值,因为我想编写一个通用的AppleScript例程来将记录和列表转换为JSON,然后由脚本输出.
我知道这是一个古老的Q,但现在有可能访问键和值(10.9+).在10.9中,您需要使用Scripting库来进行此运行,在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
Run Code Online (Sandbox Code Playgroud)
这不是黑客或解决方法.它只是使用"新"功能从AppleScript访问Objective-C-Objects.在搜索其他主题时发现此Q并无法拒绝回答;-)
更新以提供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
Run Code Online (Sandbox Code Playgroud)
玩得开心,迈克尔/汉堡
如果您只想迭代记录的值,您可以执行以下操作:
tell application "iPhoto"
repeat with value in (properties of album 1) as list
log value
end repeat
end tell
Run Code Online (Sandbox Code Playgroud)
但我不太清楚你真正想要实现什么。
| 归档时间: |
|
| 查看次数: |
4114 次 |
| 最近记录: |