Apr 03
Let's assume you have a JSON object with a predictable structure. Let's also assume you need a way to retrieve the value a specific field, at any given depth, dynamically. That is, you don't know ahead of time exactly which field's value you need. The query will be generated at run time.
JSONQuery allows you to access the value of a specific field of a JSON object by applying a query string written in JavaScript syntax.
Here's a simple example of JSONQuery in action:
var json = {
'name': 'Bob',
'address': [
{
'street': '1234 Main St.',
'city' : 'New York',
'state': 'NY',
'zip': '10101'
},
{
'street': '5678 First St.',
'city' : 'San Francisco',
'state': 'CA',
'zip': '94126'
}
]
};
var query = 'address[1].zip',
val = jsonQuery(json, query);
console.log(val); // 94126
I realize at first glance it may seem silly to even go down this path. But the need arose recently where I needed something just like this. It may still be silly, but it works damn well. If you have suggestions or improvements, please share.
Full JSONQuery code:
function jsonQuery(json, query) {
var params = query.split('.'),
result = json;
for (var i = 0, length = params.length; i < length; ++i) {
var parts = params[i].split('['),
index = null;
for (var j = 0, len = parts.length; j < len; ++j) {
index = parts[j].replace(/\]$/, '').replace(/'/g, '');
if (!result || !result[index])
return null;
result = result[index];
}
}
return result;
}
No comments