Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting top 10 Values in a JSON File [duplicate]

This is an example of my JSON file.

[
    {"Variable":"Hello","Variable1":20}, {"Variable":"Hi","Variable1":30},
    {"Variable":"How","Variable1":40}, {"Variable":"Who","Variable1":50},
    {"Variable":"Where","Variable1":60}, {"Variable":"This","Variable1":100},
    {"Variable":"Pork","Variable1":10}, {"Variable":"Creep","Variable1":90},
    {"Variable":"Mega Creeps","Variable1":80}, {"Variable":"LOL","Variable1":0},
    {"Variable":"ROFL","Variable1":0}, {"Variable":"LMAO","Variable1":0},
    {"Variable":"POP","Variable1":0}, {"Variable":"LOVE","Variable1":0},
    {"Variable":"PICK","Variable1":0}, {"Variable":"WHIZ","Variable1":0},
    {"Variable":"BORED","Variable1":0}, {"Variable":"KILLAH","Variable1":0},
    {"Variable":"LOLLING","Variable1":0}, {"Variable":"HALOO  HALOO","Variable1":0}
]

How can I get only the Top 10 from highest Variable1 number to the least? But gonna be passing the JSON file as the same format.

like image 518
Gio Perez Avatar asked Dec 15 '14 08:12

Gio Perez


People also ask

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid.

What is toJSON () in JSON?

toJSON() calls the object's toISOString() method, which returns a string representing the Date object's value. This method is generally intended to, by default, usefully serialize Date objects during JSON serialization, which can then be deserialized using the Date() constructor or Date. parse() as the reviver of JSON.

Can we have duplicate keys in JSON?

I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this.


2 Answers

First, parse the JSON into an array of Objects:

var data = JSON.parse(json);

Then combine sort and slice to achieve your goal:

var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
                .slice(0, 10);

See Array.sort

like image 69
haim770 Avatar answered Oct 11 '22 03:10

haim770


You can do it with Alasql JavaScript library. It download json file, parse it, and run SQL statement on it. This is a sample how to take top 10 directly from JSON file:

<script src="alasql.min.js></script>
<script>
    alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){
        console.log(top10);
    });
</script>

Or if you already have data in memory:

    var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
    var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);

Try this sample in jsFiddle.

like image 24
agershun Avatar answered Oct 11 '22 05:10

agershun