json - 如何在 AppleScript 中枚举记录的键和值

标签 json applescript 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:{}}

如何迭代返回记录的键/值对,以便我不必确切知道记录中的键是什么?

为了澄清这个问题,我需要枚举键和值,因为我想编写一个通用的 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/

相关文章:

objective-c - Swift/Objective-C/Applescript 项目中无法识别的选择器

macos - 如何通过 AppleScript 设置当前 Mail.app 外发消息的发件人?

Applescript:从 ApplescriptObjC 询问 Finder?

php - PHP 中的 RestAPI 设计——创建对象的对象而不是对象数组

mysql - 从 json 文件创建表

javascript - 防止在 Javascript 中使用 for-in 循环进行排序

objective-c - 像从 cmd+tab 一样获取 ProcessList

jquery - 根据温度范围更改背景颜色

xcode - 如何自动化 XCode 项目变更?

multithreading - 使用 applescriptobjc 实现 GDC