Tip: Use JSON to store complex objects
December 30th, 2007 | Published in Google Desktop API
As I develop gadgets, I often want to store complex objects — not just isolated strings or numbers — for use across sessions. For example, consider arrays. When you want to store an array in the options object, your first impulse might be to create an entry for every array item, but in most cases that's not the best solution; you'd need to remember the new storage hierarchy and include additional information, such as array lengths, in separate entries.
You can avoid these problems using an elegant solution: JSON (JavaScript Object Notation). JSON provides an intuitive, human-readable way to represent objects, which makes JSON easy to test and debug. With JSON you can serialize an object and its content into an easy-to-store string. When you want to retrieve the information, just de-serialize the string back into the original object. You can do all this and more with the functions defined in a public domain .js file, which you can include in a gadget in the same way that you include main.js. For more information and examples of using JSON, see JSON in JavaScript.
Have a tip you'd like to share? Send it to gd-developer AT google DOT com.