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.
We can have duplicate keys in a JSON object, and it would still be valid.
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.
I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With