user2058234 user2058234 - 3 months ago 7
HTML Question

Parsing JSON data based on partial element response

I have a JSON response with around 10,000 responses in it all in this particular format

{"SessionName": "rdp-tcp", "userid": "TEST:3:09-48-16-04-48-00", "ComputerName": "SERVER1", "LogonTime": "2016-08-09T04:48:00"}


I would like to be able to pull out the responses that fit a certain criteria based on a match of a partial response

For example what i am trying to get is all the Logons that occured during 4am-5am

This could be achieved by being able to query on the following:

"LogonTime": "2016-08-09T04:48:00"


How can I with (for example with Javascript) match against a partial or startswith style query in JSON to pull out all responses that fit a particular chunk of text?

Thanks in advance!

Answer

You can use Array.prototype.filter() to filter your array based on the LogonTime, getting the hour with Date.prototype.getUTCHours():

var json = [{
        "SessionName": "rdp-tcp",
        "userid": "TEST:3:09-48-16-04-48-00",
        "ComputerName": "SERVER1",
        "LogonTime": "2016-08-09T02:48:00"
    }, {
        "SessionName": "rdp-tcp",
        "userid": "TEST:3:09-48-16-04-48-00",
        "ComputerName": "SERVER1",
        "LogonTime": "2016-08-09T03:48:00"
    }, {
        "SessionName": "rdp-tcp",
        "userid": "TEST:3:09-48-16-04-48-00",
        "ComputerName": "SERVER1",
        "LogonTime": "2016-08-09T04:48:00"
    }],
    arrResult = json.filter(function(elem) {
        var date = new Date(elem.LogonTime),
            hour = date.getUTCHours();
        return hour >= 4 && hour <= 5;
    });

console.log(arrResult);

Note that as @Maxx pointed on his comment you should implement this logic on server side and for performance do some pagination because 10,000 is a very large number.