Getting top 10 Values in a JSON File
本问题已经有最佳答案,请猛点这里访问。
这是我的JSON文件的一个例子。
1 2 3 4 5 6 7 8 9 10 11 12 | [ {"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} ] |
我怎样才能从最高的变量1中得到前10个?但将以相同的格式传递JSON文件。
首先,将JSON解析为一个对象数组:
1 | var data = JSON.parse(json); |
然后结合
1 2 | var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; }) .slice(0, 10); |
号
请参见array.sort
您可以使用alasql javascript库来完成这项工作。它下载JSON文件,解析它,然后运行上面的SQL语句。下面是如何直接从JSON文件中获取前10个示例:
1 2 3 4 5 | <script src="alasql.min.js> alasql("SELECT TOP 10 * FROM JSON('mydata.json') ORDER BY Variable1 DESC",[], function(top10){ console.log(top10); }); |
或者,如果内存中已经有数据:
1 2 | var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}]; var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]); |
。
在jsFiddle中尝试此示例。