转换JSON的格式

时间:2013-07-24 09:56:23

标签: javascript json d3.js

我对AJAX使用Fuseki查询,我希望在D3.js collapsable tree中进行可视化。但是,Fuseki以JSON代码无法识别的格式返回D3.js。像这样:

{
  "head": {
    "vars": [ "s" ]
  } ,
  "results": {
    "bindings": [
      {

        "s": {

           "type": "uri",

           "value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#FourCheesesTopping"

        },

        "p": {

           "type": "uri",

           "value": "http://www.w3.org/2000/01/rdf-schema#subClassOf"

        },

        "o": {

           "type": "uri",

           "value": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#CheeseTopping"

        }
    ]
  }
}

我需要将此JSON转换为以下格式:          {

        "name": "Pizza",
        "children": [
            {
                "name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaBase",
                "children": [
                ]
            },
            {
               "name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#PizzaTopping",
                "children": [
                    {
                        "name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#MeatTopping",
                        "children": [
                            {
                                "name": "http://www.co-ode.org/ontologies/pizza/2005/05/16/pizza.owl#HotSpicedBeefTopping"
                            }
                        ]
                    }
                ]
            }
        ]
}

我尝试过使用JSON并将其放入具有正确格式的新对象中,但它无效。这是我的代码:

            var parent = new Object();
    var childArray=[];
    var child =  [];


        function createChildObj(_children, children, depth, id, childName, parent, x, x0, y, y0){
            var childObj = new Object();
                childObj._children = _children;
                childObj.children = children;
                childObj.depth = depth;
                childObj.id =id;

                childObj.name = childName;
                childObj.parent= parent;
                childObj.x = x;
                childObj.x0 = x0;
                childObj.y = y;
                childObj.y0 = y0;   
            return childObj;

            };
            console.log(root.length)
        for (var i=0; i<root.length; i++){
            var childName = root[i]["s"]["value"];
            var childObj =  createChildObj("children",null, 1, 2, childName, parent, 190, 190, 180, 180);
            child.push(childObj);           
        }
        parent.name = "Pizza";
        parent.depth = 0;
        parent.id = 3;
        parent.children= child;
        parent.x0 = root.x0;
        parent.x = parent.x0;
        parent.y0 = root.y0;
        parent.y = parent.y0;

所以我的目标是让parent作为JSON对象,并使用正确格式的数据来解析d3。抱歉这是一团糟,多年来一直在努力学习D3,学习曲线比我预期的要陡峭。任何帮助都会很棒!欢呼声。

0 个答案:

没有答案