从外部JSON文件中播种Dashing列表

时间:2015-04-04 03:52:09

标签: ruby dashing

我是Dashing的新手(而且相对较新的Ruby),所以如果这是一个愚蠢的问题,我会提前道歉。基本上我试图让Dashing读取我每10秒更新一次的json文件。但我似乎无法阅读该文件或将其发布到我的List小部件中。

这是我的工作代码:

require 'rubygems'
require 'json'
require 'pp'

name_list = Hash.new(0)

SCHEDULER.every '10s' do
    json = File.read('list.json')
    response = JSON.parse(json)
    name_list[people] = {label: response.keys, value: response.keys[]}
    send_event('whosHere', { items: response.values })
end

和我的JSON:

{
  "Mike": "Here",
  "Jon": "Out",
}

如果您需要我的仪表板代码:

<% content_for(:title) { "My super sweet dashboard" } %>
<div class="gridster">
  <ul>
    <li data-row="1" data-col="1" data-sizex="1" data-sizey="1">
      <div data-id="whosHere" data-view="List" data-title="Who's Home" style="background-color:#96bf48;"></div>
    </li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:0)

我看到两个问题:

1)您发送了错误的对象:

response = JSON.parse(json)
name_list[people] = {label: response.keys, value: response.keys[]}
send_event('whosHere', { items: response.values })
  • name_list[people]是您处理JSON时的假设结果,但您发送的是response.values

response是您返回的已解析的JSON对象。您必须遍历response以构建要发送到List的JSON对象数组:

# new empty array of persons each time job is run
persons = []
# since your JSON file is single JSON object, using names for keys
person_names = response.keys
# for each name, do this
person_names.each do |name|
  # use the 'name' key to get the value (their status)
  person_status = response[name]
  # create new Hash/JSON object for each person
  # use "label" and "value" keys for Dashing List widget
  person = Hash.new("label",name,"value",person_status)
  # add this new person object to your persons array
  persons.push(person)
end

更新了Job,它将persons数组发送给Dashing:

require 'rubygems'
require 'json'
require 'pp'

name_list = Hash.new(0)

SCHEDULER.every '10s' do
    json = File.read('list.json')
    response = JSON.parse(json)

    persons = []
    person_names = response.keys
    person_names.each do |name|
      person_status = response[name]
      person = Hash.new("label", name, "value", person_status)
      persons.push(person)
    end

    send_event('whosHere', { items: persons })
end

2)您的JSON格式不正确。 Dashing的List小部件正在侦听带有&#34;标签&#34;的对象数组。和&#34;价值&#34;键。每个人都是一个单独的JSON对象,该人的名字将是你的&#34;标签&#34;价值,他们的地位将是他们的价值&#34;值。

以下是List小部件中的列表项HTML:

  <li data-foreach-item="items">
    <span class="label" data-bind="item.label"></span>
    <span class="value" data-bind="item.value"></span>
  </li>

每个列表项都将显示一个JSON对象:

{
  "label":"Mike",
  "value":"Here" 
}

因此,要在列表中显示Mike和Jon的状态,您需要一个包含两个JSON对象的数组:

[
    {
        "label": "Mike",
        "value": "Here"
    },
    {
        "label": "Jon",
        "value": "Out"
    }
]

这个数组将是&#34;值&#34;为你的&#34;项目&#34;您的数据对象中的键被发送到List小部件:

{
    "items": [
        {
            "label": "Mike",
            "value": "Here"
        },
        {
            "label": "Jon",
            "value": "Out"
        }
    ]
}