Skip to content

Instantly share code, notes, and snippets.

@quickredfox
Created February 23, 2012 15:17
Show Gist options
  • Save quickredfox/1893259 to your computer and use it in GitHub Desktop.
Save quickredfox/1893259 to your computer and use it in GitHub Desktop.
JSON.lookup() # find things in JSON collections
var json;
json = [
{
foo: {
bar: ['ka', 'boom']
}
}, {
foo: {
bar: ['sna', 'fu']
}
}, {
foo: {
bar: {
rab: 'oof'
}
}
}
];
console.log(JSON.lookup('foo.bar[1]=/(boom|fu)/', json, true));
/// OUTPUTS
[ {
foo: {
bar: ['ka', 'boom']
}
}, {
foo: {
bar: ['sna', 'fu']
}
} ]
/*
json-lookup v1.0
*/
!function(){
"use strict"
var getvalcheck, json, lookup, parseQuery;
getvalcheck = function(expected) {
var is_regex_match, tester;
is_regex_match = /^\/.+\/$/;
if (is_regex_match.test(expected)) {
tester = new RegExp(expected.replace(/^\/|\/$/g, ''));
return function(v) {
return tester.test(v);
};
} else {
return function(v) {
return v === expected;
};
}
};
parseQuery = function(query) {
var checkval, expected, has_value_check, paths;
has_value_check = /\=.+$/;
paths = query.replace(has_value_check, '');
paths = paths.replace(/\.(\d+)\./, "[$1]");
if (has_value_check.test(query)) {
expected = query.substring(query.indexOf('=') + 1);
checkval = getvalcheck(expected);
} else {
checkval = function() {
return true;
};
}
return {
paths: paths,
checkval: checkval
};
};
lookup = function(query, json, multiple) {
var collected, index, item, o, _len;
if (query == null) query = '';
if (json == null) json = [];
if (multiple == null) multiple = false;
if (query === '') return json;
if (!(json instanceof Array)) json = [json];
if (typeof query === 'number') return json[query];
if (typeof query === 'string') query = parseQuery(query);
collected = [];
for (index = 0, _len = json.length; index < _len; index++) {
item = json[index];
o = (new Function("try{return this." + query.paths + "}catch(E){return null}")).call(item);
if (query.checkval(o)) {
if (multiple) {
collected.push(item);
} else {
return item;
}
}
}
if (multiple) {
return collected;
} else {
return null;
}
};
if (typeof JSON.lookup !== "function") JSON.lookup = lookup;
}()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment