按字母顺序对JSON输出进行排序

时间:2019-07-13 01:39:08

标签: html json scala sorting

我正在寻求有关如何编写/修改以下代码的帮助,以便使我的JSON输出通过“货币”字段按字母顺序排序。

以下是执行JSON输出的代码:-

  def balance = Action(parse.json) { implicit request =>
    val body = request.body
    (for (
      apiKey <- (body \ "api_key").validate[String]
    ) yield {
      val balances = globals.engineModel.balance(None, Some(apiKey))
      Ok(Json.toJson(balances.map({ c =>
        Json.obj(
          "currency" -> c._1,
          "amount" -> c._2._1.bigDecimal.toPlainString,
          "hold" -> c._2._2.bigDecimal.toPlainString
        )
      })
      ))
    }).getOrElse(
      BadRequest(Json.obj("message" -> Messages("messages.api.error.failedtoparseinput")))
    )
  }

代码的第二部分是:-

    function show_balance(){
        API.balance().success(function(balances){
            for (var i = 0; i < balances.length; i++) {
                balances[i].available = zerosToSpaces(Number(balances[i].amount) - Number(balances[i].hold));
                balances[i].amount = zerosToSpaces(balances[i].amount);
                balances[i].hold = zerosToSpaces(balances[i].hold);
            }
            $('#balance').html(template(balances));
        });
    }
    show_balance();

1 个答案:

答案 0 :(得分:0)

这被标记为JavaScript,但看起来更像Scala。假设balance是具有确定顺序的类型(而不是Set),那么您应该可以进行balance.sortBy(_._1)