简体   繁体   中英

Fast retrieval of data from json object using xpath

I have a very large data set that may contains thousands of records hierarchy is

records
 ->record1
   ->main_record
   ->minor_record
        ->fields
->record2
    ->main_record
        ->data_records
            ->fields_records
                ->fields

This hierarchy can be even more rested depending upon the input file and it may contains hundreds for records like record1 record2 , here one thing I must mention that data is not sorted at level.

Now lets suppose I want to find fields in fields_record than XPath will be

record2/main_record/data_records/fields_records/fields

one way to find is to loop whole dataset and find desired record which is not affordable, the way I am using for searching data is:

function main() {
  var dataset = getDataFromService();
  getResult(dataset, xpath);
}

function getdataset(dataset, nametosearch) {
  for (var i = 0; i < dataset.length; i++) {
    if (dataset[i].name == nametosearch) {
      return dataset[i];
    }
  }
}

function getResult(dataset, xpath) {
  if (xpath.indexOf('/') > -1) {
    var splitArray[] = xpath.split("/");
    for (var i = 0; i < splitArray.length; i++) {
      dataset = getdataset(dataset, splitArray[i]);
    }
    return dataset;
  } else {
    getdataset(dataset, xpath); //else part to get records at root level
  }
}

With the above mentioned code I can get data I want to know is this way efficient? If not what would be the better option for getting data using XPath?

Try JSONPath.

Eaxmple:
Json:

{
     "firstName": "John",
     "lastName" : "doe",
     "age"      : 26,
     "address"  : {
         "streetAddress": "naist street",
         "city"         : "Nara",
         "postalCode"   : "630-0192"
     },
     "phoneNumbers": [
         {
           "type"  : "iPhone",
           "number": "0123-4567-8888"
         },
         {
           "type"  : "home",
           "number": "0123-4567-8910"
         }
     ]
 }



Path:$.phoneNumbers[:1].type

Result:"iPhone"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM