我是Rails的新手,并尝试使用Ancestry gem中的JSON在浏览器中填充jstree(请参阅https://github.com/stefankroes/ancestry)。 JSON是中间人。我被困的地方是翻译Ancestry制作的JSON(来自我的树模型):
<%= @trees.arrange_serializable.to_json %>
这给了我很好的JSON如下(仅片段,为无意义的值道歉):
[
{
"id": 2,
"name": "Milk",
"note": "No details available",
"created_at": "2014-09-20T13:22:03.262Z",
"updated_at": "2014-09-20T13:48:46.301Z",
"value": "3.06",
"ancestry": null,
"children": [
{
"id": 1,
"name": "Farms",
"note": "Some note here",
"created_at": "2014-09-20T13:05:22.186Z",
"updated_at": "2014-10-03T11:30:39.029Z",
"value": "432.0",
"ancestry": "2",
"children": [
{
"id": 8,
"name": "Zog",
"note": "Orc",
"created_at": "2014-09-27T22:11:20.874Z",
"updated_at": "2014-10-03T11:30:38.989Z",
"value": "11.0",
"ancestry": "2/1",
"children": [
{
"id": 14,
"name": "Planes",
"note": "",
"created_at": "2014-10-04T01:01:12.890Z",
"updated_at": "2014-10-04T04:51:20.873Z",
"value": "422.0",
"ancestry": "2/1/8",
"children": []
}
]
},
但是jstree插件需要JSON的特定格式,如下所示(来自http://www.jstree.com/docs/json/):
{
id : "string" // will be autogenerated if omitted
text : "string" // node text
icon : "string" // string for custom
state : {
opened : boolean // is the node open
disabled : boolean // is the node disabled
selected : boolean // is the node selected
},
children : [] // array of strings or objects
li_attr : {} // attributes for the generated LI node
a_attr : {} // attributes for the generated A node
}
虽然源层次结构是完美的,但我需要替换属性&#34; name&#34;用原文&#34;文字&#34;在输出中,加上一些其他更改。
在我的脑海里,我觉得应该有一些优雅的东西(比如XSLT for XML)将JSON#1翻译成JSON#2,但我找不到任何这样做的例子。