在Rails中向数组添加哈希

时间:2014-03-17 14:37:32

标签: ruby-on-rails arrays json hash ruby-on-rails-2

我有以下代码从api调用中获取结果并将其作为json提供给我的前端:

notes = { :notes => [] }

json['Response']['OperationResponse']['Notes']['Note'].each do |note|
    notes[:notes] << [:user => note['User'], :time_stamp => note['TimeStamp'], :text => note['Text']]
end

render :json => notes.to_json

但是我得到了这种格式:

{
    "notes": [
        [
            {
                "time_stamp": "test",
                "user": "test",
                "text": "test"
            }
        ],
        [
            {
                "time_stamp": "test",
                "user": "test",
                "text": "test"
            }
        ],
        ....

而不是这种期望的格式:

{
    "notes": [
        [
            {
                "time_stamp": "test",
                "user": "test",
                "text": "test"
            },

            {
                "time_stamp": "test",
                "user": "test",
                "text": "test"
            },
            ....

1 个答案:

答案 0 :(得分:1)

尝试

json['Response']['OperationResponse']['Notes']['Note'].each do |note|
    notes[:notes] << {:user => note['User'], :time_stamp => note['TimeStamp'], :text => note['Text']}
end

您正在将元素作为数组[]推送,而是使用{}