将属性添加到json文件

时间:2017-10-30 16:20:27

标签: json scala apache-spark intellij-idea

我有一个格式为

的json文件
{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear"},{"time":1462683600,"summary":"Clear",},{"time":1462694400,"summary":"Clear"}]}}

我想在数据

中添加id属性
val result = jsonfile

val Jsonobject = Json.parse(result).as[JsObject]

val res = Jsonobject ++ Json.obj("id" -> 1234)

println(Json.prettyPrint(res))

输出应为

{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear","id":"1234"},{"time":1462683600,"summary":"Clear","id":"1235"},{"time":1462694400,"summary":"Clear","id":"1236"}]}

但我的输出是

{"latitude":28.488069,"longitude":-81.407208,"data":[{"time":1462680000,"summary":"Clear"},{"time":1462683600,"summary":"Clear",},{"time":1462694400,"summary":"Clear"}]},"id":"1234"}

1 个答案:

答案 0 :(得分:1)

您的代码中缺少一些内容。在您的预期输出中,ID会增加,您希望如何添加"id" -> 1234并自动增加?

无论如何,你必须循环遍历data中的元素并为它们中的每一个设置它。这样的事情有效:

    val j = Json.parse(result).as[JsObject]
    val res = j ++ Json.obj("data" ->  
      // get the 'data' array and loop inside
          (j \ "data").as[JsArray].value.zipWithIndex.map {  
      // zipWithIndex lets us use the index to increment the ID
      case (x,i) => x.as[JsObject] +  ("id" , JsString((1234 + i).toString)) })
    println(Json.prettyPrint(res))

{
  "latitude" : 28.488069,
  "longitude" : -81.407208,
  "data" : [ {
    "time" : 1462680000,
    "summary" : "Clear",
    "id" : "1234"
  }, {
    "time" : 1462683600,
    "summary" : "Clear",
    "id" : "1235"
  }, {
    "time" : 1462694400,
    "summary" : "Clear",
    "id" : "1236"
  } ]
}