问题
Below is a sample of final json I pass to javascript. I will use the (yajl) ruby library to create this json from a hash.
The question is what should a ruby hash that produces the json below look like?
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"}}
]
}
]
}];
回答1:
Your question is not too clear. Do you mean what is the Ruby structure that would create the JSON you show in your question?
If so, then here you go.... Note that the base-level structure is a Ruby Array because your JSON base level structure is also an Array.
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"}
}]
}]
}]
回答2:
- Copy your code (exactly) after the
var
and before the;
- Paste into Ruby (1.9+)
At this point you are done. To prove it... require "json"
puts data.to_json
Result (with extra linebreaks):
#=> [{"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:
You can find out what sort of data structure would produce that JSON yourself easily enough:
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
And then a quick reformatting of the output gives you this:
[
{
"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" => { }
}
]
There are probably easier ways but the above will do for a quick one-shot hack.
回答4:
I just ran that in my browser and it appears to be valid JSON. Is that your question?
来源:https://stackoverflow.com/questions/5812789/what-is-the-hash-structure-to-produce-json