假设我的数据库中有两个表,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 |
+------------+----------------+
车:
table
我想将此架构导出到JSON对象,以便我可以根据表格填充HTML下拉菜单 - 例如,employee
菜单将car
和{{1} }。选择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"
}
]
}
答案 0 :(得分: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);
}