这是我的JSON文件的一个示例。
[
{"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}
]
如何才能从最高的Variable1号码中获得前10名?但是要将JSON文件作为相同的格式传递。
答案 0 :(得分:16)
首先,将JSON解析为一个Objects数组:
var data = JSON.parse(json);
然后合并sort
和slice
以实现您的目标:
var top10 = data.sort(function(a, b) { return a.Variable1 < b.Variable1 ? 1 : -1; })
.slice(0, 10);
请参阅Array.sort
答案 1 :(得分:3)
您可以使用Alasql JavaScript库执行此操作。它下载json文件,解析它,然后运行 关于它的SQL语句。这是一个如何直接从JSON文件中获取前10名的示例:
<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>
或者如果你已经在内存中有数据:
var data = [{"Variable":"Hello","Variable1":20},{"Variable":"Hi","Variable1":30}];
var res = alasql("SELECT TOP 10 * FROM ? ORDER BY Variable1 DESC",[data]);
在jsFiddle中尝试this sample。