2013-08-05 15 views
3

當我使用的AppleScript得到一個對象的屬性,一個記錄返回。如何枚舉記錄的鍵和值的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然後可以通過腳本輸出。

+0

如果我理解了這個問題,這聽起來像你想要做的事情是:1)獲取關鍵字列表,2)確定你感興趣的關鍵字併爲該關鍵字的名稱分配一個變量,然後3)查找對應於該鍵的值。根據[this](http://macscripter.net/viewtopic.php?id=22437)有沒有簡單的方法來做到這一點與蘋果,雖然一些黑客可能是 –

+0

AppleScript記錄是固定的屬性集合類似於C結構,而不是像Perl哈希或Python字典這樣的任意鍵值集合。由於AppleScript缺乏內省,因此沒有內置的方法來提取屬性名稱列表。有各種各樣的黑客和雜誌可以使用,但他們都很討厭和/或不可靠。正如其他人所說,目前尚不清楚爲什麼你希望這樣做,而不是使用該語言作爲其設計用途。 – foo

+0

@foo不幸的是,我認爲你的評論是我正在尋找的答案。但是,我不能接受評論作爲答案。您是否介意將評論發佈爲答案,以便其他人可以從被接受的答案中獲益? –

回答

2

如果你只是想通過記錄的值進行迭代,你可以做這樣的事情:

tell application "iPhoto" 
    repeat with value in (properties of album 1) as list 
     log value 
    end repeat 
end tell 

但它不是我很清楚你真正想要達到的目標。

1

基本上,AtomicToothbrush和foo說的是什麼。 AppleScript記錄更像C結構,帶有已知的標籤列表,而不像關聯數組,具有任意鍵,並且沒有(體面的)內部語言方式來反省記錄上的標籤。 (即使有,你仍然有應用它們來獲取值的問題。)

在大多數情況下,答案是「使用關聯數組庫」。但是,您特別感興趣的是來自properties值的標籤,這意味着我們需要黑客。通常一個是使用記錄來強制錯誤,然後解析錯誤消息,像這樣:

set x to {a:1, b:2} 
try 
    myRecord as string 
on error message e 
    -- e will be the string 「Can’t make {a:1, b:2} into type string」 
end 

解析這一點,尤其是在分析此同時允許非英語語言環境,是留給作爲練習爲讀者。

3

我知道這是一個老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 

這不是砍或變通方法。它只是使用「新」功能從AppleScript訪問Objective-C對象。 尋找其他議題過程中發現這個Q和無法抗拒回答;-)

更新提供JSON功能: 當然,我們可以深入探討的基礎類,並使用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 

玩得開心,邁克爾/漢堡

+0

這正是我想到的。但是,你是否真的試着用「獲得......的屬性」而不是構建一個。 – markhunte

+0

對不起,最近的回答是:謝恩斯坦利自己說:「腳本橋不能處理這樣的記錄條目(如果你明白幕後涉及到什麼,你可能會對腳本橋有些同情)」 - 我相信他: -D – ShooTerKo

1

ShooTerKo的回答是難以置信的幫助我。

我會提出另一種可能性,我很驚訝我沒有看到其他人提到,但。我的AppleScript和JSON之間走了很多我的劇本,如果你能在需要運行該腳本的計算機上,那麼我強烈建議JSONHelper上安裝軟件,基本上使整個問題消失:

https://github.com/isair/JSONHelper

+0

這個應用程序非常酷,它也可以在Mac App Store中使用。它會自動更新,然後;-) – ShooTerKo