Created
April 10, 2011 01:19
-
-
Save tmzt/911955 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createPath(data, path) { | |
var object = data; | |
var existing = findExisting(data, path); | |
console.log('existing: ', existing); | |
if (existing != '') { | |
object = data; | |
var value = jsonPath(data, existing); | |
if (typeof(value) != 'boolean') { | |
if (typeof(value.length) != 'undefined') value = value[0]; | |
object = value; | |
}; | |
path = path.replace(new RegExp('^'+existing), ''); | |
path = path.replace(/^\./, ''); | |
}; | |
console.log('new path: ', path); | |
return createChildPath(object, path); | |
}; | |
function createChildPath(object, path) { | |
console.log('object: ', object); | |
console.log('child path: ', path); | |
if (path == '') return object; | |
var parts = path.split(/\./); | |
var rmn = parts.slice(1,parts.length).join('.'); | |
var elm = parts[0]; | |
if(elm.match(/^\[(\d)+\]$/)) { | |
var elmparts = elm.match(/\[(\d)+\]/); | |
if (elmparts.length) { | |
var idx = elmparts[1]; | |
console.log('idx: ', idx); | |
var nobject = object[idx] = new Object(); | |
return createChildPath(nobject, rmn); | |
}; | |
} else if(elm.match(/([$_a-zA-Z]+)\[(\d+)]$/)) { | |
var elmparts = elm.match(/([$_a-zA-Z]+)\[(\d+)]$/); | |
console.log('elmparts: ', elmparts); | |
if (elmparts.length > 1) { | |
var nm = elmparts[1]; | |
var idx = elmparts[2]; | |
console.log('nm: ', nm); | |
console.log('idx: ', idx); | |
var arr = object[nm] = new Array(); | |
var nobject = arr[idx] = new Object(); | |
return createChildPath(nobject, rmn); | |
}; | |
} else { | |
var nobject = object[elm] = new Object(); | |
return createChildPath(nobject, rmn); | |
} | |
}; | |
function findExisting(data, path) { | |
console.log('path: ', path); | |
/* if there are no more elements, we're done */ | |
if (path == '') return ''; | |
/* if it exists, we're done */ | |
var value = jsonPath(data, path); | |
console.log('value: ', value); | |
if (typeof(value) == 'undefined') return ''; | |
if (typeof(value) != 'boolean') return path; | |
/* if not, remove array index */ | |
if(path.match(/\]$/)) { | |
path = path.replace(/\[.+\]$/, ''); // remove any array index | |
return findExisting(data, path); | |
}; | |
/* now remove path elements */ | |
var parts = path.split(/\./); | |
var parts = parts.slice(0, parts.length-1); | |
return findExisting(data, parts.join('.')) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment