按字段值过滤json-map对象,即Some(value)
Filtering json-map objects by fields value, which is Some(value)
有一个 json 文件超过 10000 行。您可以看到以下数据格式:
{"id":1,"child_id":1822925634,"parent_id":-1,"name":"victor"}
{"id":2,"child_id":1266710134,"parent_id":25,"name":"victor"}
{"id":3,"child_id":572534000,"parent_id":-1,"name":"simone"}
.
.
.
{"id":10575,"child_id":572534781,"parent_id":135,"name":"victor"}
我想过滤所有 parent_id 等于 -1.
的行
首先,我的代码读取文件内容,然后通过换行符将其拆分。
val file = new File("./myFile.json")
val jsonContent = FileUtils.readFileToString(file)
JSON.globalNumberParser = {input : String => Integer.parseInt(input)}
val jsonArray = jsonContent.split("\n").map(x=>JSON.parseFull(x).get.asInstanceOf[Map[String,String]])
到目前为止,我有一个包含 4 个键值对的地图对象(到目前为止一切正常)。稍微调试一下,tempreturns"Some(-1)"如预期。
val temp = jsonArray(2).get("parent_id")
现在,我想根据parent_id
过滤json数组
val selectedRows = jsonArray.filter(_.get("parent_id")=="-1").map(_.get("name"))
但它 returns 是一个空的地图对象。问题是方程不满足。我试过 ("parent_id")=="-1" 或 "Some(-1)" 或 Some(" -1")
Map.get
returns 一个 Option
因此你的表达式 _.get("parent_id")=="-1"
总是 false
.
您需要将其转换为 _.get("parent_id") == Some(-1)
。
有一个 json 文件超过 10000 行。您可以看到以下数据格式:
{"id":1,"child_id":1822925634,"parent_id":-1,"name":"victor"}
{"id":2,"child_id":1266710134,"parent_id":25,"name":"victor"}
{"id":3,"child_id":572534000,"parent_id":-1,"name":"simone"}
.
.
.
{"id":10575,"child_id":572534781,"parent_id":135,"name":"victor"}
我想过滤所有 parent_id 等于 -1.
的行首先,我的代码读取文件内容,然后通过换行符将其拆分。
val file = new File("./myFile.json")
val jsonContent = FileUtils.readFileToString(file)
JSON.globalNumberParser = {input : String => Integer.parseInt(input)}
val jsonArray = jsonContent.split("\n").map(x=>JSON.parseFull(x).get.asInstanceOf[Map[String,String]])
到目前为止,我有一个包含 4 个键值对的地图对象(到目前为止一切正常)。稍微调试一下,tempreturns"Some(-1)"如预期。
val temp = jsonArray(2).get("parent_id")
现在,我想根据parent_id
过滤json数组val selectedRows = jsonArray.filter(_.get("parent_id")=="-1").map(_.get("name"))
但它 returns 是一个空的地图对象。问题是方程不满足。我试过 ("parent_id")=="-1" 或 "Some(-1)" 或 Some(" -1")
Map.get
returns 一个 Option
因此你的表达式 _.get("parent_id")=="-1"
总是 false
.
您需要将其转换为 _.get("parent_id") == Some(-1)
。