将ruby哈希格式化为json

时间:2015-05-14 00:14:59

标签: ruby-on-rails arrays ruby json

我目前正致力于将一些数据从ruby格式化为json; 我目前的代码看起来像这样

def line_chart_data
    @sources = ['Facebook','Twitter','Instagram','LinkedIn']
    @sourceCount = [5,12,16,6]
    @weeks = ['one','two','three','four','five','six']

    h = []
    @weeks.each do |i,v|
        h.push({'v' => 'Week ' + i})
        @sourceCount.each do |s|
             h.push({'v' => s})
        end
    end
    c = {c: h}


    #How the data should be formatted on export
    @sources2 = {
      cols: [
        {label: 'Week', type: 'string'},
        #Each Source needs to be looped though and formatted
        {label: 'Facebook', type: 'number'},
        {label: 'Twitter', type: 'number'},
        {label: 'Instagram', type: 'number'},
        {label: 'LinkedIn', type: 'number'}
      ],
      rows: c
     }



    respond_to do |format|
        format.js {render json: @sources2}
    end
end

当数据打印到控制台时,它看起来像这样(为了简洁起见,将其缩短了一点)

"rows":{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6},
{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6},
{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}

如果您注意到第一个" c"打开一个数组但是当它循环上面的代码时,它不会为每周创建一个新数组。代码看起来应该更像这样。

"rows":{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6}],
{"c":[{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6}]},
{"c":[{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}

其中,周数组的每个循环都创建一个新的哈希,其键为" c"和数组的值。

非常感谢任何帮助我指向正确方向的帮助!已经坚持了很长一段时间。

1 个答案:

答案 0 :(得分:1)

您需要重新编写代码才能获得此代码。你想要的JSON实际上是无效的,所以这是你可以得到的最接近的:

"rows":[{"c":[{"v":"Week one"},{"v":5},{"v":12},{"v":16},{"v":6}],
{"c":[{"v":"Week two"},{"v":5},{"v":12},{"v":16},{"v":6}]},
{"c":[{"v":"Week three"},{"v":5},{"v":12},{"v":16},{"v":6}]}]

代码:

rows = []
@weeks.each do |i,v|
    h = []
    h.push({'v' => 'Week ' + i})
    @sourceCount.each do |s|
         h.push({'v' => s})
    end
    rows.push({"c" => h})
end



#How the data should be formatted on export
@sources2 = {
  cols: [
    {label: 'Week', type: 'string'},
    #Each Source needs to be looped though and formatted
    {label: 'Facebook', type: 'number'},
    {label: 'Twitter', type: 'number'},
    {label: 'Instagram', type: 'number'},
    {label: 'LinkedIn', type: 'number'}
  ],
  rows: rows
 }