2011-03-02 44 views
0

我有一個由nokogiri返回的錨標記數組,我需要將它們強制轉換爲值的哈希以便將它們輸出爲JSON。在這個過程中,我還需要添加一些鍵/值對。這個更大的目的是創建一個JSON集合,用於爲Google Chrome手動構建書籤文件。 Chrome的書籤文件是這樣的:獲取一個Ruby對象數組(從nokogiri)到JSON

{ 
    "checksum": "xxxxxxxxxxxxxxxxxxx", 
    "roots": { 
     "bookmark_bar": { 
      "date_added": "12941058862382319", 
      "id": "1101", 
      "name": "One Site", 
      "type": "url", 
      "url": "http://www.onesite.com/" 
     }, { 
      "date_added": "12941058862383177", 
      "id": "1102", 
      "name": "Two Site", 
      "type": "url", 
      "url": "http://www.twosite.com" 
     } ], 
     "date_added": "11644473600000000", 
     "date_modified": "12941058862390426", 
     "id": "1", 
     "name": "Bookmarks Bar", 
     "type": "folder" 
     } 
    ... and so on 

我的錨標籤將提供名稱和URL,然後DATE_ADDED,可以添加id和類型值。

我假設我需要以某種方式使用Array.map,但是我的技能不存在,並且在閱讀其他幾個網站解釋它之後,我仍然無法接近如何使用它在我的情況。

所有我能想出是這樣的:

Hash[ bookmarks.map{ |bookmark| bookmark.content, bookmark.xpath("@href") }.to_json ] 

但抱怨不能夠將字符串轉換爲整數,所以這顯然不是去了解它的正確方法。

感謝您的任何幫助。

回答

0

好吧,我想我現在已經明白了。這應該工作

bookmarks.map{ |x| Hash["date_added" => "12941058862385244", "id" => bookmarks.index(x), "name" => x.content, "type" => "url", "url" => x.xpath("@href")] } 

我們會看到Chrome瀏覽器在去使用它,但是當我使用JSON.pretty_generate輸出它看起來不錯。