am trying to fetch the data from sql server 2008 via Node using Drivers. Somehow i can get the data successfully.. My Question is how to display it in Json format.
My code is like this:
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);
});
Right now my results after querying the database is like this:
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
Suggest me something...
JSON stringify has an arg to prettify and indent. This will print and indent each level 2 spaces.
console.log(JSON.stringify(myObject, null, 2);
So this:
var obj = ['one', 'two', {a:1, b:2}];
console.log(JSON.stringify(obj, null, 2));
Outputs:
[
"one",
"two",
{
"a": 1,
"b": 2
}
]
If the raw object contains more data than you want or you want to be selective, or you want control on how the JSON obj to output is built, then you can copy data into a new object then pretty print that. also note that your SQL result set is flat so mod'ing as you loop allows you to build it into objects. Something like ...
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;
}
}
});
if you want to log out every row as a single object do it like this
execSql("select * from tblStudent", function (err,rows) {
rows.forEach(function (row) {
console.log(row);
});
});
or formatted like bryanmac proposed:
execSql("select * from tblStudent", function (err,rows) {
rows.forEach(function (row) {
console.log(JSON.stringify(row, null, 2));
});
});