假设我的数据库中有两个表,employee
和car
这样定义的。
员工:
+--------------+------------+
| 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
菜单将具有 employee
和 car
。选择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);
}