3

I currently have a key/value table in my rails application and I am trying to export all the rows in a key => value array format when I ask for the JSON format.

The closest I can get is

{
    navigationBarColor: "#E31937"
},
{
    navigationBarImage: "Background-NavBar"
},

But I would only like to get an array of key/value pair, not an object for each. I was looking for something like

"navigationBarColor":"#E31937",
"navigationBarImage":"Background-NavBar",

My table only has a key and a value column, both in varchar.

Any help would be greatly appreciated.

Update: My serializable_hash looks like this now:

def serializable_hash()
    {key => value}
end
4

1 回答 1

1

You're looking for a :reduce via :merge.

> rows = [{ navigationBarColor: "#E31937" }, { navigationBarImage: "Background-NavBar" }]
=> [{:navigationBarColor=>"#E31937"}, {:navigationBarImage=>"Background-NavBar"}]

> rows.reduce(&:merge!)
=> {:navigationBarColor=>"#E31937", :navigationBarImage=>"Background-NavBar"}

> puts rows.reduce(&:merge!).to_json
{"navigationBarColor":"#E31937","navigationBarImage":"Background-NavBar"}
于 2013-06-06T15:24:39.357 回答