2

我是新来的斯卡拉。我正在尝试使用 json 文件进行简单的操作。我被以下任务困住了:如何在具有定义名称的对象中优雅地删除具有定义名称的字段。例如,我想从对象 name2 中删除 dsc1 字段

{
  "group": {
    "name1":{
      "dsc":"some dsc",
      "dsc1":"some dsc",
      "dsc2":"some dsc"
     },
    "name2":{
      "dsc":"some dsc",
      "dsc1":"some dsc",
      "dsc2":"some dsc"
    }
  }
}

对于解析,我使用的是 liftweb。我已经创建了以下代码,但它删除了所有 dsc1:

val transformedJson2 = parsedInput transform { 
    case JObject(fields) if (fields.head.name == "name2") => JObject(fields) transform {
          case JField("dsc1", JArray(xs)) =>  JNothing
}
4

2 回答 2

4

我稍微改写了你的转换,当我根据你的输入尝试它时,这似乎奏效了:

val transformedJson2 = parsedInput transform { 
  case JField("name2", fields) => 
    fields remove {
      case JField("dsc1", _) =>  true
      case _ => false   
    }
}

除了使用,您还可以像在示例中那样remove使用第二个:transform

val transformedJson2 = parsedInput transform { 
  case JField("name2", fields) => 
    fields transform {
      case JField("dsc1", _) =>  JNothing
    }
}

因此,通过使用来自以下的解析输入:

scala> val parsedInput = parse(""" {
     |   "group": {
     |     "name1":{
     |       "dsc":"some dsc",
     |       "dsc1":"some dsc",
     |       "dsc2":"some dsc"
     |      },
     |     "name2":{
     |       "dsc":"some dsc",
     |       "dsc1":"some dsc",
     |       "dsc2":"some dsc"
     |     }
     |   }
     | } """)
parsedInput: net.liftweb.json.package.JValue = JObject(List(JField(group,JObject(List(JField(name1,JObject(List(JField(dsc,JString(some dsc)), JField(dsc1,JString(some dsc)), JField(dsc2,JString(some dsc))))), JField(name2,JObject(List(JField(dsc,JString(some dsc)), JField(dsc1,JString(some dsc)), JField(dsc2,JString(some dsc))))))))))

两者都应该产生输出:

scala> pretty(render(transformedJson2))
res10: String = 
{
  "group":{
    "name1":{
      "dsc":"some dsc",
      "dsc1":"some dsc",
      "dsc2":"some dsc"
    },
    "name2":{
      "dsc":"some dsc",
      "dsc2":"some dsc"
    }
  }
}
于 2013-01-08T18:22:11.563 回答
0

我试过这个:

 val transformedJson2 = parsedInput transformField {
    case JField("group", fields) => (
      "group", fields transformField {
         case JField("name2", nameFields) => ( 
             "name2", nameFields removeField {
               case JField("dsc1", _) => true    
               case _ => false
             }
         )
      }     
    )
}

println(compact(render(transformedJson2)))
于 2017-10-10T16:37:13.730 回答