开发者

Multiple keyword (that has regex) search through JSON

I have some JSON that looks like:

"groups": [

  "group_id": "8",
  "group_name": "Building",
  "group_color": "00ff00"
},
{
  "group_id": "3",
  "group_name": "Building",
  "group_color": "8000ff"
},
{
  "group_id": "2",
  "group_name": "Sidewalk",
  "group_color": "ff0000"
},
{
  "group_id": "6",
  "group_name": "Parking Lot",
  "group_color": "00ffff"
},
{
  "group_id": "3",
  "group_name": "Commons",
  "group_color": "ff8000"
},
{
  "group_id": "5",
  "group_name": "Other",
  "group_co开发者_JS百科lor": "ff00ff"
}
]

And when a field is found it flips a boolean flag.

e.g.

for (var c=0; c<json.groups.length; c++) {
   inSearch = false;
   if(json.groups.group_id.match(query)!=null){
      inSearch = true;
   }
}

However, if query = Building then I return two results, so what I'm looking to do is set query = Building&8 to return only the first result.

Note: query can also be a regular expression which I think is where this should go...

Any ideas?

EDIT: Is there a way to, say, split my string into parts and then match a single object based on two different pieces of that object? So match the first object based on either group_id and group_color, or match it based on group_name and group_color?


For present case something like this should work:

data = JSON.parse('your_json');
for (var i=0, j=data.length; i<j; i++){
    var inSearh = false;
    if(data[i].group_id===8 && data[i].group_name==="Something"){
    inSearch = true;
    break;
    }
}

For a more general case you can wrap it in a function:

key_tester = function(jsonData,key1, value1, key2, value2){
    // Here jsonData is parsed JSON
    for(var i=0, j=jsonData.length; i<j; i++){
        var obj = jsonData[i];
        if(obj[key1] == value1 && obj[key2] == value2){
            return true; 
     }
     return false;
}

Then you can use it like:

jsonData = JSON.parse('Your json');
if (key_tester(jsonData, "group_id","8","group_name","building"))
   // Here goes your awesome code

You can extend the key_tester function to include more key value pairs.

This should save us from going the regex way.


This is your object.

var jsonObj = {
"groups": [
    {
    "group_id": "8",
    "group_name": "Building",
    "group_color": "00ff00"},
{
    "group_id": "3",
    "group_name": "Building",
    "group_color": "8000ff"},
{
    "group_id": "2",
    "group_name": "Sidewalk",
    "group_color": "ff0000"},
{
    "group_id": "6",
    "group_name": "Parking Lot",
    "group_color": "00ffff"},
{
    "group_id": "3",
    "group_name": "Commons",
    "group_color": "ff8000"},
{
    "group_id": "5",
    "group_name": "Other",
    "group_color": "ff00ff"}
]
};

This function checks that your object properties satisfy the regular expressions defined in regsObj.

/**
 * Check that an obejct matches all the 
 * regexp defined in the regsObj
 */
 var matchRegObj = function(obj, regsObj) {
     var matched = false,
         regExp;

    for (var propName in regsObj) {
       regExp = regsObj[propName];
       matched = regExp.test(obj[propName]);

       if (matched !== true) {
          break;
       }
    }

    return matched;
};

The function test return your matching object.

  /**
   * Return the first object matching all the regexp rule
   * defined in the regsObj.
   */
  var test = function(jsonObj, regsObj) {
    var matched = false,
        obj;

    for (var i = 0;  i < jsonObj.groups.length && !matched; i++) {
       obj = jsonObj.groups[i];
       matched = matchRegObj(obj, regsObj);
    }

    return (matched) ? obj : {};
};

In regsObject you define the reg-exps that the searched object in groups list must satisfy.

/**
 * regsObj is only a container of propertyName and regexp used to query the right object.
 */
var regsObj = {
   "group_id" : "10",
   "group_name" : "Building" 
};

Search your object in this way.

 /**
  * @param {Object} jsonObjyour Your json Object.
  * @param {Object} regObj The object holding all the regular expressions.
  * @return {Object} your matching object
  */
 var result = test(jsonObj, regsObj);
 console.dir(result);


SortingHat - you can use this JS lib, DefiantJS (http://defiantjs.com) , and let it do the "heavy lifting" for you. That way, you code is more clean and can look like this:

var data = {
   "groups": [
      { "group_id": "8", "group_name": "Building",    "group_color": "00ff00" },
      { "group_id": "3", "group_name": "Building",    "group_color": "8000ff" },
      { "group_id": "2", "group_name": "Sidewalk",    "group_color": "ff0000" },
      { "group_id": "6", "group_name": "Parking Lot", "group_color": "00ffff" },
      { "group_id": "3", "group_name": "Commons",     "group_color": "ff8000" },
      { "group_id": "5", "group_name": "Other",       "group_color": "ff00ff" }
   ]
},
res = JSON.search( data, '//*[group_name="Building" and group_id=8]' )
output = document.getElementById('output');

output.innerHTML = JSON.stringify( res[0], null, '   ' );
output.style.backgroundColor = '#'+ res[0].group_color;

Here is working fiddle:
http://jsfiddle.net/hbi99/3Ry4L/

DefiantJS extends the global object JSON with the method "search" - with which queries can be made on JSON structure with XPath expressions.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜