As I said in the comments, you can use a simple reviver function within the JSON parsing, as long as you keep the keys in mind. See this jsFiddle: http://jsfiddle.net/38Ytc/3/
This is an example, let's suppose you got the JSON string somewhere (in the example, from a textbox), and you need to add certain functions to the objects returned by this data. We then call parse
with an reviver function as the second argument, that will be called for each key within the data structure. For our minimal example, it would convert all non-array objects except the top level object (key "") to a DataRow object, which has the methods get
, set
and save
.
var inputEl = $("#exampleInput");
var outputEl = $("#exampleOutput");
function DataRow(contents) {
this.object = contents;
}
DataRow.prototype.get = function(key) {return key?this.object[key].object:this.object;};
DataRow.prototype.set = function(key, val) {if (key) {this.object[key] = val;} else {this.object = val;};};
DataRow.prototype.save = function() {/*Save to DB or whatever*/};
inputEl.change(function() {
var resultObject = JSON.parse( inputEl.val(),function(key, val) {
if (key === "" || typeof val === Array) { //See MDN for why this is necessary
return val;
} else {
return new DataRow(val);
}
});
console.log(resultObject.entries.object[0].get("title"));
outputEl.val(JSON.stringify(resultObject));
});
After this processing, you could simply use resultObject.entries.object[0].get("title")
to get a object's title, if it exists.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse