以 JSON 表示数据库架构



假设我的数据库中有两个表,employeecar这样定义的。

员工:

+--------------+------------+
|   col_name   | data_type  | 
+--------------+------------+
| eid          | int        |
| name         | string     |
| salary       | int        |
| destination  | string     |
+--------------+------------+

汽车:

+------------+----------------+
|  col_name  |   data_type    |
+------------+----------------+
| cid        | int            |
| name       | string         |
| model      | string         |
| cylinders  | int            |
| price      | int            |
+------------+----------------+

我想将此架构导出到 JSON 对象,以便我可以根据表填充 HTML 下拉菜单 - 例如,table菜单将具有 employeecar 。选择employee将使用与该表对应的列名称和类型填充另一个下拉列表。

给定此用例,数据库的最佳 json 表示形式是这样的吗?

{
    "employee": {
        "salary": "int", 
        "destination": "string", 
        "eid": "int", 
        "name": "string"
    }, 
    "car": {
        "price": "int", 
        "model": "string", 
        "cylinders": "int", 
        "name": "string", 
        "cid": "int"
    }
}

编辑:还是这样更合适?

{
    "employee": [
        {
            "type": "int", 
            "colname": "eid"
        }, 
        {
            "type": "string", 
            "colname": "name"
        }, 
        {
            "type": "int", 
            "colname": "salary"
        }, 
        {
            "type": "string", 
            "colname": "destination"
        }
    ], 
    "car": [
        {
            "type": "int", 
            "colname": "cid"
        }, 
        {
            "type": "string", 
            "colname": "name"
        }, 
        {
            "type": "string", 
            "colname": "model"
        }, 
        {
            "type": "int", 
            "colname": "cylinders"
        }, 
        {
            "type": "int", 
            "colname": "price"
        }
    ]
}

在第一个示例中,所有数据都存储在对象中。假设结构存储在 var mytables 中,你可以得到带有 Object.keys(mytables) 的名称,返回 ['employee', 'car'] 。等效于内部的列:Object.keys(mytables['employee'].cols)返回['salary','destination','eid','name']

在第二个示例中,我建议也将表作为列存储在数组中,例如

[name: 'employee', 
 cols: [ {
           "type": "int", 
           "colname": "cid"
         }, ...]

然后,您可以轻松迭代数组并通过访问mytables[i].name获取名称

for (t in tables){
  console.log(tables[t].name);
  for (c in tables[t].cols)
    console.log(" - ",tables[t].cols[c].colname, ": ", tables[t].cols[c].type);
}

最新更新