2017-08-08 66 views
0

我使用軌道4,並得到下面的來自不同源的合併JSON陣列與對象 - 的Rails 4-紅寶石

source1中

@something1 = book.find().to_json 

輸出

"[{\"a\": \"val1\"}]" 

源2輸出JSON

@something2 = Author.where(title: :autitle).pluck(:val2).to_json 

輸出

"[{\"b\": \"val2\"}]" 

源3

@something3 = Publications.find_by_pub_id(id) 

輸出

{ 
    "c":"val3", 
    "d":" val4" 
} 

我要像

{ 
    "a": "val1", 
    "b": "val2", 
    "c":"val3", 
    "d":" val4" 
} 
最終輸出像

@newval= @something1[0].merge(@something2[0]).merge(@something3) 

我已經使用合併但是,它給了錯誤

未定義的方法合併!

這些變量指數法裏像

class Test controller < api::controller 
    def index 
    @something1 = .. 
    @something2 = .. 
    @something3 = .. 
    end 
end 

希望這是顯而易見的。

+0

您可以包括完整的日誌/錯誤信息?用提供的例子[熊的回答](https://stackoverflow.com/a/45567464/6136634)工作正常(你可以看到它在[這裏](https://repl.it/KB2T/0)(https://repl.it/KB2T/0)),所以也許你在'@ something'變量中獲得了不同的輸出。 – Gerry

+0

@Gerry雖然這個例子很好(和功能),也許我們應該清楚,問題中的**輸出**是不準確的。 JSON是一個'String',因此第一個例子的正確輸出實際上是'「[{\」a \「:\」val1 \「}]」'。 '字符串'沒有'合併'方法,如果OP發佈了完整的消息,那麼這種方法會更加明顯。例如'未定義的方法合併!爲「[{\」a \「:\」val1 \「}]」:String' *編輯問題的正確輸出* – engineersmnky

+0

@Khoga從前兩個移除'to_json'調用並將其添加到合併的末尾鏈。見[Gerry's repl的更新版本](https://repl.it/KB2T/2) – engineersmnky

回答

1

你的問題就在這裏是JSON是a String因此

@something1 = book.find().to_json 
#=> "[{\"a\": \"val1\"}]" 

當試圖將它們「合併」在一起時,這會使處理變得更加困難。

您收到的錯誤是因爲String沒有merge方法(下次請發佈完整錯誤或至少是對象引用)例如,undefined method merge! for "[{\"a\":\"val1\"}]":String

幸運的是,解決方法是非常簡單的只是從原來的2個呼叫爲刪除to_json這樣

require 'json' 

@something1 = [{"a": "val1"}] # no to_json 
@something2 = [{"b": "val2"}] # no to_json 
@something3 = { "c": "val3", "d": " val4" } # no to_json 

@something1[0].merge(@something2[0]).merge(@something3).to_json 
#=> "{\"a\":\"val1\",\"b\":\"val2\",\"c\":\"val3\",\"d\":\" val4\"}" 

Example(基於@格里原來的註釋過的例子)

因爲這似乎軌喜歡,我們可以如果我們理解了Book,AuthorPublication之間的關係,可能會簡化整個過程。

Book.find().to_json(include: [:author,:publications]) 
# Or 
Book.find().to_json(include: [{author: {only: :name}},:publications]) 

這將避免需要合併,因爲我怕原來的例子可能實際上需要

@something1 = book.find() 
@something2 = book.author 
@something3 = book.publications 

@something1.attributes.merge({author: @something2.attributes, 
    publications: @something3.map(&:attributes)}).to_json 
2

由於沒有更多的信息,這似乎足以

@something1[0].merge(@something2[0]).merge(@something3) 
{ 
    :a => "val1", 
    :b => "val2", 
    :c => "val3", 
    :d => " val4" 
} 
+0

我已更新我的問題。如果您需要更多信息,請告訴我。 – Khoga

1

您可以創建這樣一個功能:

def mergejson(*args) 
    merged = {} 
    args.each do |a| 
    merged.merge!(a.is_a?(Hash) ? a : a.first) 
    # or use .deep_merge! if the hashes can contain nested hashes 
    end 
    return merged 
end 

irb(main):025:0> test = mergejson(something1, something2, something3) 
=> {:a=>"val1", :b=>"val2", :c=>"val3", :d=>"val4"} 
0

此外,通過工作:

@something1.first.merge(@something2.first).merge(@something3) 

#=>{:a => "val1",:b => "val2",:c => "val3",:d => " val4"} 
+0

這與[Ursus提供的](https://stackoverflow.com/a/45567464/6136634)的答案几乎相同。 – Gerry