【问题标题】:Representing a DB schema in JSON用 JSON 表示数据库模式
【发布时间】:2018-04-13 13:55:20
【问题描述】:

假设我的数据库中有两个表,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"
        }
    ]
}

【问题讨论】:

  • 您的问题到底是什么,如果示例 json 是最佳表示形式?鉴于您描述的用例,我认为这是一个合适的表示。
  • 谢谢@martink - 我已经添加了另一个 JSON 结构 - 如果可以选择哪个最合适?

标签: json hive


【解决方案1】:

在第一个示例中,您的所有数据都存储在对象中。假设结构存储在 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);
}

【讨论】:

    猜你喜欢
    • 2011-10-02
    • 2017-04-18
    • 1970-01-01
    • 2011-05-22
    • 2013-07-03
    • 2016-05-09
    • 2011-01-22
    • 1970-01-01
    • 2012-01-17
    相关资源
    最近更新 更多