【问题标题】:Extract type, key and value from Rapture JSON object从 Rapture JSON 对象中提取类型、键和值
【发布时间】:2016-01-03 14:12:05
【问题描述】:

我正在使用带有 Argonaut 后端的 Rapture JSON(如有必要,可以更改)。

给定一个任意 JSON 字符串,我需要将其解析为平面对象(没有嵌套的 JSON 对象)以理想地获得 元组列表 (fieldName, fieldType, fieldValue) 每个字段。

import rapture.json._
import rapture.json.jsonBackends.argonaut._

val j = json"""{"what":"stuff"}"""
val extracted: List[(String, FieldType, Any)] = j.someMagic()

// So I can do this
extracted.map { _ match {
  case (k, JString, v) => println("I found a string!")
  ...
}}

更新:这变成了 rapture-json 中的 github issue

【问题讨论】:

    标签: json scala argonaut rapture.io


    【解决方案1】:

    我直接使用 Argonaut 解决了这个问题。所有这些选项和 scalaz 析取有点残酷,欢迎改进

    import rapture.json._
    import rapture.json.jsonBackends.argonaut._
    
    val parsed: Disjunction[String, argonaut.Json] = argonaut.Parse.parse(
      """{"what":"stuff", "num": 1, "bool":true}""")
    
    
    val fieldzAndValues: Disjunction[String, Option[List[(argonaut.Json.JsonField, argonaut.Json)]]] = for {
      jo <- parsed
      flds = jo.hcursor.fields
      vls = jo.objectValues
    } yield vls.map( v => flds.map(_.zip(v))).flatten
    
    fieldzAndValues.toOption.flatten.map(_.map(_ match {
      case (k, v) if(v.isString) => s"$k string $v" 
      case (k, v) if(v.isBool) => s" $k bool $v" 
      case (k, v) if(v.isNull) => s"$k null $v" 
      case (k, v) if(v.isNumber) => s" $k number $v" 
    }))
    // res0: Option[List[String]] = Some(List(what string "stuff",  num number 1,  bool bool true))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-05
      • 2016-12-24
      • 1970-01-01
      • 2021-03-10
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-12
      相关资源
      最近更新 更多