[英]Formatting ruby hash to json
I am current working on formatting some data from ruby into json; 我目前正在将一些数据从ruby格式化为json; My current code looks like this
我当前的代码如下所示
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
when the data gets printed to the console it looks like this (shortened it a little for brevity) 当数据打印到控制台时,它看起来像这样(为简洁起见,将其缩短了一点)
"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}]}
If you notice the first "c" opens with an array but as it loops through the above code it does not create a new array for each week. 如果您注意到第一个“ c”以一个数组打开,但是在遍历上面的代码时,它不会为每个星期创建一个新的数组。 The code should look more like this.
该代码应看起来像这样。
"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}]}
Where each loop of weeks array creates a new hash with a key of "c" and a value of array. 其中,每星期循环数组将使用键“ c”和数组值创建一个新的哈希。
any help pointing me in the right direction is greatly appreciated! 非常感谢您为我指明正确的方向! Been stuck on this for quite a while.
坚持了一段时间。
You will need to re-work your code a bit to get this. 您将需要对代码进行一些重做才能做到这一点。 The JSON you want is actually not valid, so this is the closest you can get:
您想要的JSON实际上是无效的,因此这是您可以获得的最接近的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}]}]
Code: 码:
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.