API Development

How-To: Persist Complex JavaScript Objects

Everyone who has developed a Titanium application is likely familiar with the Properties API, which allows you to store key/value pairs without needing to use a local SQL database to store that information.  This is a great way to store a few configuration options, but once your application needs to store more than a couple values, storing each value individually can be a bit tedious.

However, if you combine the Properties API with Titanium’s built in JSON serialization capabilities, you can create a very flexible means of storing complex JavaScript objects.  Let’s say we have a JavaScript object which contains user preferences for a game we’re writing in Titanium:

var userProfile = {
  handle: "megaGamer17",
  soundVolume: 10,
  fullGore: true,
  achievements: ["most_deadly", "lemming", "flawless_victory"],
  xboxLive: {
    username:"handyManny12",
    someRanking:12
  }
};

So we have quite a bit of configuration information about our user, and the structure is complex enough where it would be annoying to have to model it in a relational database. This is the perfect situation to use JSON+Properties to store this information. To persist this JavaScript object, you would combine the two APIs like so:

Ti.App.Properties.setString("userProfile", JSON.stringify(userProfile));

This is using the built in JSON namespace to convert the userProfile JavaScript object to a string, and then storing that string in a property so we can access it later. To pull the data back out again, we do something very similar:

var userProfile = JSON.parse(Ti.App.Properties.getString("userProfile"));

Now we have a fully hydrated JavaScript object to work with. The other benefit of using this approach over a SQL database or individual properties is that your data structure is easy to evolve. So if your user profile changes to allow additional properties, like:

var userProfile = {
  handle: "megaGamer17",
  first_name: "Kevin",
  last_name: "Whinnery",
  soundVolume: 10,
  fullGore: true,
  achievements: ["most_deadly", "lemming", "flawless_victory"],
  xboxLive: {
    username:"handyManny12",
    someRanking:12
  }
};

You don’t have to worry about migrating your database or adding code to access additional properties – you can just start using those properties in your code right away (bearing in mind that if you’re updating an app in production, those values will be undefined initially). It’s not rocket science, but this technique is just the ticket for storing complex objects without having to resort to a SQL database.