我正在尝试使用Drivers通过Node从sql server 2008获取数据。不知何故,我可以成功获取数据..我的问题是如何以Json格式显示它。
我的代码是这样的:
execSql("select * from tblStudent", function (err,rows) {
console.log("City_StrCode:" + rows[0].value);
console.log("State_StrCode:" + rows[1].value);
console.log("City_StrName:" + rows[2].value);
});
现在我查询数据库后的结果是这样的:
City_StrCode:0005
State_StrCode:ORS
City_StrName:Ratnagiri12
City_StrCode:1002
State_StrCode:78899
City_StrName:thousandtwo
City_StrCode:1010
State_StrCode:1001
City_StrName:U FOOL34
Status:true
City_StrCode:105
State_StrCode:001
City_StrName:dgrt12
City_StrCode:1789
State_StrCode:001
City_StrName:XZAS12
建议我......
答案 0 :(得分:4)
JSON stringify有一个美化和缩进的arg。这将打印并缩进每个2级空格。
console.log(JSON.stringify(myObject, null, 2);
所以这个:
var obj = ['one', 'two', {a:1, b:2}];
console.log(JSON.stringify(obj, null, 2));
输出:
[
"one",
"two",
{
"a": 1,
"b": 2
}
]
如果原始对象包含的数据多于您想要的数据,或者您希望选择性,或者您希望控制如何构建JSON obj输出,那么您可以将数据复制到新对象中然后打印出来。另请注意,您的SQL结果集是扁平的,因此您循环的mod'ing允许您将其构建为对象。有点像...
execSql("select * from tblStudent", function (err,rows) {
for (i=0; i<rows.length; i++) {
var output;
var fieldNum = i % 3;
switch (fieldNum){
case 0:
output = {};
output.cityCode = rows[i].value;
break;
case 1:
output.stateCode = rows[i].value;
break;
case 2:
output.stateName = rows[i].value;
console.log(output, null, 2);
break;
}
}
});
答案 1 :(得分:2)
如果你想将每一行注销为单个对象就像这样
execSql("select * from tblStudent", function (err,rows) {
rows.forEach(function (row) {
console.log(row);
});
});
或格式化为bryanmac建议:
execSql("select * from tblStudent", function (err,rows) {
rows.forEach(function (row) {
console.log(JSON.stringify(row, null, 2));
});
});