ActiveRecord
查询的结果是一个散列数组。如果我只是将其转换为 JSON 输出,哈希的键(数据库列名称)将在每一行的 JSON 结果中重复。例如。 Dailystats.all.to_json
返回:
[
{\"statisticsDate\":1360454400000,\"storageTopTempAvg\":48.6},
{\"statisticsDate\":1360540800000,\"storageTopTempAvg\":49.0},
{\"statisticsDate\":1360627200000,\"storageTopTempAvg\":48.4}
]
但是我想省略重复的列名并只得到这个:
[
{1360454400000:48.6},
{1360540800000:49.0},
{1360627200000:48.4}
]
有没有一种简单的方法可以做到这一点,还是我应该构建一个数据转换器?
最佳答案
您应该能够在将数据转换为 json 之前映射数据:
Dailystats.all.map {|item| {item[:statisticsDate] => item[:storageTopTempAvg]}}.to_json
关于ruby-on-rails - 哈希 to_json : how can I skip the key and list only the values in the JSON response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14877369/