I'd like to format my query results as a single JSON object containing an array object for each record. Need help writing the script though - the JSON.stringify function is building an array of objects (My JSON is inside out!).
I can always write a function to build the JSON manually but I have a feeling there's already a function to do what I'm looking for. I just can't find it.
The JSON string I want to get:
{["id":1,"info":"Ipsum 0"], ["id":2,"info":"Ipsum 1"],
["id":3,"info":"Ipsum 2"], ["id":4,"info":"Ipsum 3"] (and so on) }
Actual Results
[{"id":1,"info":"Ipsum 0"},{"id":2,"info":"Ipsum 1"},
{"id":3,"info":"Ipsum 2"},{"id":4,"info":"Ipsum 3"},
{"id":5,"info":"Ipsum 4"},{"id":6,"info":"Ipsum 5"},
{"id":7,"info":"Ipsum 6"},{"id":8,"info":"Ipsum 7"},
{"id":9,"info":"Ipsum 8"},{"id":10,"info":"Ipsum 9"}]
My code so far (based on this example)
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database(':memory:');
db.serialize(function() {
db.run("CREATE TABLE lorem (info TEXT)");
var stmt = db.prepare("INSERT INTO lorem VALUES (?)");
for (var i = 0; i < 10; i++) {
stmt.run("Ipsum " + i);
}
stmt.finalize();
var sql = "SELECT rowid AS id, info FROM lorem";
// Print the records as JSON
db.all(sql, function(err, rows) {
console.log(JSON.stringify(rows));
});
});
db.close();
Based on what I know of JSON I was expecting the whole recordset to be enclosed with curly brackets, and each record to be enclosed with a square bracket. However I'm seeing the opposite.
Nope, you have it backward. Database results will be modeled as an array of objects - 1 array represents the results of the entire query, and each object in that array represents a single result record. In JSON, Arrays use square brackets, objects use curly braces (Same as actual JavaScript code).