我是 Rails 新手,并试图在浏览器中使用 Ancestry gem 中的 JSON 填充 jstree(请参阅https://github.com/stefankroes/ancestry)。JSON是中间人。我被卡住的地方是翻译 Ancestry 生成的 JSON(来自我的 Tree 模型):
<%= @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
}
虽然源层次结构是完美的,但我需要将原始中的属性“名称”替换为输出中的“文本”,以及其他一些更改。
在我的脑海里,我觉得应该有一些优雅的东西(比如用于 XML 的 XSLT)将 JSON#1 转换为 JSON#2,但我找不到任何这样做的例子。