Skip to content

To JSON or not to JSON

January 18, 2012

How to simply convert a sqlite database to JSON

Last week my collegue Matteo (aka pupunzi) was porting an iPad application (booo!) to HTML5 (yeah!).

The iPad application was a virtual museum that was using a sqlite dabatase for reading data relative to rooms, biography, history and so on.

Even if sqlite is internally supported by some browsers (e.g. Chrome) the easiest way to read data in javascript is to have a JSON object.

I wrote a simple java code to dump the whole database into a JSON object.

import net.sf.json.JSONObject;
import net.sf.json.JSONArray;
import java.sql.*;
import java.util.List;
import java.util.ArrayList;
import java.io.FileOutputStream;
public class DB2JSON {

  public static void main(String[] args) {

    if (args.length<1)
      return;
    Connection conn = null;

    try {
      String dbFile = args[0];
      JSONObject ret = new JSONObject();
      Class.forName("org.sqlite.JDBC");
      conn = DriverManager.getConnection("jdbc:sqlite:" + dbFile);
      Statement stat = conn.createStatement();

      ResultSet tables = stat.executeQuery("SELECT name 
         FROM sqlite_master 
         WHERE type='table' ORDER BY name;");
      List tableNames = new ArrayList();
      while (tables.next()) {
        tableNames.add(tables.getString("name"));
      }
      tables.close();

      for (String tableName : tableNames) {
        JSONArray jsa = new JSONArray();

        ResultSet rows = stat.executeQuery("select * from " + 
           tableName + ";");

        while (rows.next()) {
          JSONObject row = new JSONObject();
          ResultSetMetaData meta = rows.getMetaData();
          for (int i = 1; i <= meta.getColumnCount(); i++) {
            row.element(meta.getColumnName(i), rows.getObject(i));
          }
          jsa.add(row);
        }

        rows.close();
        ret.element(tableName, jsa);
      }

      conn.close();

      // result on console
      System.out.println(ret.toString());

      //result on file
      FileOutputStream fos = new FileOutputStream(dbFile+".json");
      fos.write(ret.toString().getBytes());
      fos.close();     

    } catch (Throwable e) {
      try {
        if (conn != null)
          conn.close();
      } catch (SQLException s) {
      }
      e.printStackTrace();
    }
  }
}

The resulting JSON object will have a property for each table containing an array of records. Different types of properties are supported (String, int, long, dates etc.)

There are two dependencies to external libraries:

  1.  http://json-lib.sourceforge.net/
  2. http://www.zentus.com/sqlitejdbc/

Enjoy.

P.S.: the pupunzi’s porting result is an HTML5 application that runs everywhere and it is looks even more beautiful than the iOS one Smile !

2 Comments leave one →
  1. May 24, 2012 21:26

    what if I have foreign key relationships on the database? I need to get an object inside an object or list of objects inside an object depending on one-to-one or one-to-many relationship.

    • May 25, 2012 09:48

      I think your problem cannot be resolved with (a simple) general solution. Having a foreign key doesn’t mandatory means the best mapping is to have a collection inside the object (e.g.: your foreign-object could be referenced by another one); you could need a “link” object.

      This problem is known as “ORM” see http://en.wikipedia.org/wiki/Object-relational_mapping.

      In those cases I add a prototyped function to the object, that finds the foreign object by id.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: