frenetix
frenetix

Reputation: 1209

validating JSON file in JavaScript

My Google Chrome extension uses JSON.parse(oldJSONstring) to create an object with configuration information. The "oldJSONstring" was saved from previous sessions on Chrome's localStorage.

As I sometimes add new features, after I create the new object, I manually validate that all configuration entries exist, if not, I'll set them with default values. This is done, in case it's he firs time a user loads the extension after it updated.

I was trying to think of a more automatic way of doing this, like using a JSON Schmea, but I really don't know where to start, and my first round of google searches didn't produce anything I could use.

Another approach I thought was to iterate on all my Default settings -also stored on a JSON object- and then confirming they exist on the new object... but I just realized I don't know how to iterate a JSON object for all its attributes :)

The end goal of this is that I'd like to forget about validating for new attributes, every time I create a new feature and I publish a new version... does it make any sense? does it make me lazy? :D

Thanks!

Upvotes: 0

Views: 255

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Keep the default object handy and use jQuery $.extend to merge the 2 objects.

var defaults={ color:'blue', size:'Large'}

var chromeObj= /* code to grab from storage*/
/* update chromeObj with all key/value pairs in defaults */
 /*  regardless if they already exist or not*/
$.extend( chromeObj, defaults}

/* code to put chromeObj back to storage*/

Refrence: http://api.jquery.com/jQuery.extend/

Upvotes: 2

jonvuri
jonvuri

Reputation: 5930

There is no such thing as a "JSON object,"* but it's quite easy to loop over a Javascript object's properties: How do I loop through or enumerate a JavaScript object?

* JSON is just a string format, and it's a subset of Javascript object notation

Upvotes: 1

Related Questions