下面是我传递给javascript的最终json示例。我将使用(yajl)ruby库从哈希创建这个json。
问题是,产生json的 ruby hash 应该是什么样的?
var data = [{
data: "basics",
attr: {},
children: [
{data: "login", attr: {run: "run"},
children: [
{data: "login", attr: {}}
]
} ,
{data: "Academic Year", attr: {run: "run"},
children: [
{data: "login", attr: {}},
{data: "Academic Year", attr: {filter: "mini", SOF: "yes"}}
]
}
]
}];
答案 0 :(得分:4)
var
之后和;
require "json"
puts data.to_json
结果(带有额外的换行符):
#=> [{"data":"basics","attr":{}, "children":[
#=> {"data":"login","attr":{"run":"run"},"children":[
#=> {"data":"login","attr":{}}
#=> ]},
#=> {"data":"Academic Year","attr":{"run":"run"},"children":[
#=> {"data":"login","attr":{}},
#=> {"data":"Academic Year","attr":{"filter":"mini","SOF":"yes"}}
#=> ]}
#=> ]}]
答案 1 :(得分:3)
你可以很容易地找出哪种数据结构可以很容易地产生JSON:
require 'active_support'
json = '[{
data: "basics",
attr: {},
children: [
{data: "login", attr: {run: "run"},
children: [
{data: "login", attr: {}}
]
} ,
{data: "Academic Year", attr: {run: "run"},
children: [
{data: "login", attr: {}},
{data: "Academic Year", attr: {filter: "mini", SOF: "yes"}}
]
}
]
}]'
puts ActiveSupport::JSON.decode(json).inspect
然后快速重新格式化输出就可以了:
[
{
"data" => "basics",
"children" => [
{
"data" => "login",
"children" => [
{
"data" => "login",
"attr" => { }
}
],
"attr" => {
"run" => "run"
}
},
{
"data" => "Academic Year",
"children" => [
{
"data" => "login",
"attr" => { }
},
{
"data" => "Academic Year",
"attr" => {
"filter" => "mini",
"SOF" => "yes"
}
}
],
"attr" => {
"run" => "run"
}
}
],
"attr" => { }
}
]
可能有更简单的方法,但上述方法可以快速实现一次性攻击。
答案 2 :(得分:1)
你的问题不太清楚。你是说什么是Ruby结构会创建你在问题中显示的JSON?
如果是这样,那么你去....注意,基本级结构是一个Ruby数组,因为你的JSON基本级结构也是一个数组。
mydata = [{
'data' => "basics",
'attr' => {},
'children' => [{
'data' => "login",
'attr' => {'run' => "run"},
'children' => [{
'data' => "login",
'attr' => {}
}]
},
{
'data' => "Academic Year",
'attr' => {'run' => "run"},
'children' => [{
'data' => "login",
'attr' => {}
},
{
'data' => "Academic Year",
'attr' => {'filter' => "mini",
'SOF' => "yes"}
}]
}]
}]
答案 3 :(得分:-1)
我刚刚在浏览器中运行它,它似乎是有效的JSON。那是你的问题吗?