2015-12-21 63 views
1

我有一個大JSON對象本身(但X100 +):蛻變散列結構

[ 
    { 
     "category": "category1", 
     "text": "some text" 
    }, 
    { 
     "category": "category2", 
     "text": "some more text" 
    }, 
    { 
     "category": "category1", 
     "text": "even more text" 
    } 
] 

如何將蛻變到這一點:

{ 
    "category1": [ 
     { 
      "text": "some text" 
     }, 
     { 
      "text": "even more text" 
     } 
    ], 
    "category2": { 
     "text": "even more text" 
    } 
} 

在正確的方向的任何幫助,將不勝感激。

+2

您是不是要找' 「類別2」:{ 「文」: 「一些文字」}'?在第二個樣本? – quetzalcoatl

+1

邏輯不清楚。 – sawa

+2

@quetzalcoatl或者''category2「:[{」text「:」更多文本「}]'在邏輯上會更加一致。 – sawa

回答

1

首先,您需要將您的JSON字符串轉換爲Ruby對象。

require "json" 
json = %{ 
[ 
    { 
     "category": "category1", 
     "text": "some text" 
    }, 
    { 
     "category": "category2", 
     "text": "some more text" 
    }, 
    { 
     "category": "category1", 
     "text": "even more text" 
    } 
] 
} 
ary = JSON.parse(json) 

現在,我們已經在Ruby的形式哈希值的數組,我們可以操縱它

h = ary.group_by {|i| i["category"]} 
#=> {"category1"=>[{"category"=>"category1", "text"=>"some text"}, {"category"=>"category1", "text"=>"even more text"}], "category2"=>[{"category"=>"category2", "text"=>"some more text"}]} 

h = h.map {|k,v| {k => v.map {|t| {"text" => t["text"]}}}} 
#=> [{"category1"=>[{"text"=>"some text"}, {"text"=>"even more text"}]}, {"category2"=>[{"text"=>"some more text"}]}] 

h = h.reduce(&:merge) 
#=> {"category1"=>[{"text"=>"some text"}, {"text"=>"even more text"}], "category2"=>[{"text"=>"some more text"}]} 

打印JSON在美麗的形式,檢查結果

puts JSON.pretty_generate(h) 

輸出:

{ 
    "category1": [ 
    { 
     "text": "some text" 
    }, 
    { 
     "text": "even more text" 
    } 
    ], 
    "category2": [ 
    { 
     "text": "some more text" 
    } 
    ] 
} 
+0

而不是在圍欄上折騰代碼,而是解釋爲什麼代碼是合適的。不要發放魚,教人們如何釣魚,這樣他們就能知道下一次該做什麼,並且可以建立它。 –

+0

其實,感謝魔杖製造商。看到它實際工作是我理解它的最好方式。謝謝! – oorahduc

+0

@theTinMan謝謝。在這個擴展了一點,將來會嘗試更精細 –

0

Enumerable#each_with_object可能會有所幫助。類似於

json.each_with_object({}) do |h, acc| 
    acc[h[:category]] ||= [] 
    acc[h[:category]] << {text: h[:text]} 
end # {"category1"=>[{:text=>"some text"}, {:text=>"even more text"}], "category2"=>[{:text=>"some more text"}]} 

其中json是您的原始數組。

1

假設得到的結果"category2": [{"text": "some more text"}]

array.map(&:dup).group_by{|h| h.delete(:category)} 
+1

我想你的意思是'array.map(&:dup).group_by {| h | h.delete(:category)}''' 令人印象深刻的是它的簡潔程度,但它不是OP所要求的100%:http://rubysandbox.com/#/snippet/56785144793916000c000001 – cthulhu

+0

@cthulhu對。謝謝你糾正我。 – sawa

+0

沒關係我對你的評論代碼沒有做到100%是什麼意圖 - 我認爲我們有ruby哈希,但實際上它是JSON ... – cthulhu