如何从JSON中获取n个随机元素

时间:2016-03-29 19:02:01

标签: javascript

我有以下JSON结构,我想抓住每个类别(area_description)的n个随机元素,而不是在d3可视化中显示所有内容。我能达到的最干净的方式是什么?我的想法是按区域描述对JSON进行排序,得到每个类别的开始和结束,然后抓取元素。

[

{

    "id": ​1,
    "number": "2-1",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "High Perfomance Computing",
    "status": "ASSIGNED"

},
{

    "id": ​2,
    "number": "2-2",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "High Perfomance Computing",
    "status": "AVAILABLE"

},
{

    "id": ​3,
    "number": "2-3",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Cloud",
    "status": "AVAILABLE"

},
{

    "id": ​4,
    "number": "2-4",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Cloud",
    "status": "AVAILABLE"

},
{

    "id": ​5,
    "number": "2-5",
    "type": "GENERAL",
    "location": "US2",
    "floor": ​2,
    "area_description": "Static",
    "status": "ASSIGNED"

}]

1 个答案:

答案 0 :(得分:0)

我写了函数,也许它不是那么干净,试试这个:

static final String PREFIX = "ORDER WILL SHIP _";
String s = // file content
value = s.substring(s.indexOf(PREFIX) + PREFIX.length(), s.indexOf("_ WORKING DAYS"));