获取 JSON 文件中的前 10 个值 [重复]
Posted
技术标签:
【中文标题】获取 JSON 文件中的前 10 个值 [重复]【英文标题】:Getting top 10 Values in a JSON File [duplicate] 【发布时间】:2015-02-13 07:05:33 【问题描述】:这是我的 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
]
我怎样才能只获得从变量 1 数字最高到最少的前 10 个?但是会以相同的格式传递 JSON 文件。
【问题讨论】:
【参考方案1】:首先,将 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
【讨论】:
比较中有错字。应该是a.Variable1 > b.Variable1
不,拥有a.Variable1 > b.Variable1
将显示生成数组并显示最低值。旧帖子,但可能对想要节省一分钟的人有所帮助。【参考方案2】:
您可以使用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。
【讨论】:
有什么办法可以用php实现这个吗?? 不错的图书馆,感谢分享以上是关于获取 JSON 文件中的前 10 个值 [重复]的主要内容,如果未能解决你的问题,请参考以下文章