如何从元素获取JSON路径

时间:2016-10-09 08:47:45

标签: javascript json d3.js svg backbone.js

我已经实现了一个递归的javascript函数,通过读取JSON模式在svg中绘制以下结构,如下所示。

有没有办法确定所选节点的JSON路径?比如,当用户点击一个节点(比如LoadLibrary)时,有没有办法返回JSON路径(country:string)?

更新:我使用主干模型,因此我的解决方案是跟踪并添加JSON路径作为节点的属性以供以后使用。我正在寻找其他直接方法。

person.address.country

enter image description here

递归代码(骨干函数)如下:

{
  "title": "person",
  "type": "object",
  "properties": {
    "first name": { "type": "string" },
    "last name": { "type": "string" },
    "age":{ "type":"number"},
    "birthday": { "type": "string", "format": "date-time" },
    "address": {
      "type": "object",
      "properties": {
        "street address": {
      "type": "object",
      "properties": {
        "house number": { "type": "number" },
        "lane": { "type": "string" }
      }    
    },
        "city": { "type": "string" },
        "state": { "type": "string" },
        "country": { "type" : "string" }
      }    
    },
    "phone number": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string"
          },
          "code": {
            "type": "number"
          }
        },
        "required": [
          "location",
          "code"
        ]
      }
    },
    "children": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "nickname":{"type":"string"}
  }
}

1 个答案:

答案 0 :(得分:2)

你可以使用特殊的治疗途径来连接。

function getPath(object, search) {
    function iter(o, p) {
        return Object.keys(o).some(function (k) {
            if (k === key && o[k] && o[k].type === value) {
                path = p.concat(k).join('.');
                return true;
            }
            if (o[k] !== null && typeof o[k] === 'object') {
                return iter(o[k],
                    k === 'properties' && !o.title ?
                        p :
                        p.concat(k === 'properties' && o.title ? o.title : k)
                );
            }
        });
    }

    var parts = search.split(':'),
        key = parts[0],
        value = parts[1],
        path;

    iter(object, []);
    return path;
}

var data = { title: "person", type: "object", properties: { "first name": { type: "string" }, "last name": { type: "string" }, age: { type: "number" }, birthday: { type: "string", format: "date-time" }, address: { type: "object", properties: { "street address": { type: "object", properties: { "house number": { type: "number" }, lane: { type: "string" } } }, city: { type: "string" }, state: { type: "string" }, country: { type: "string" } } }, "phone number": { type: "array", items: { type: "object", properties: { location: { type: "string" }, code: { type: "number" } }, required: ["location", "code"] } }, children: { type: "array", items: { type: "string" } }, nickname: { type: "string" } } };

console.log(getPath(data, 'country:string'));
.as-console-wrapper { max-height: 100% !important; top: 0; }