3

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();
5
  • What's surprising about the result being an array of objects? Commented Jul 18, 2013 at 18:44
  • Maybe I am converting it to JSON with the wrong function. I would like to see the results in the format I described. Commented Jul 18, 2013 at 18:56
  • Again: what's surprising about this? Do you have good knowledge of the JSON format? Commented Jul 18, 2013 at 19:00
  • Re-stated question more clearly Commented Jul 18, 2013 at 19:14
  • The output you're asking for isn't valid json Commented Jul 18, 2013 at 20:42

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.