Scala-从包含JSON格式数据的文件中提取值 [英] Scala - Extracting a value from a file containing data in JSON format

查看:759
本文介绍了Scala-从包含JSON格式数据的文件中提取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个"sample.json"文件,其中包含以下JSON数据:

I have a 'sample.json' file containing the following JSON data:

{"query": "SELECT count(*)  FROM TABLE_NAME"}

此文件是由另一个应用程序生成的,并放置在该应用程序目录中.

This file is being generated by another application and is placed in that application directory.

我要做的是读取此文件并将键"query"的值(即TABLE_NAME中的SELECT count(*))提取到val query中.此val query将用于查询数据库.

What I want to do is to read this file and extract the value (i.e., SELECT count(*) FROM TABLE_NAME) of the key 'query' into a val query. This val query will be used to query a database.

作为Scala的新手,我对找到的其他答案相当迷失. 在Scala中将文件中的值提取到val query的最简单方法是什么?

Being new to Scala, I am quite lost in the other answers I have found. What is the simplest way to extract the value from the file into val queryin Scala?

除非有必要,我宁愿不使用任何外部库.

I would prefer not using any external libraries unless very necessary.

推荐答案

在scala中有无数种解析JSON的方法.对于您的特定任务,这里有一个建议,假设您的JSON字符串已被读入变量jsonStr:

There are countless ways of parsing JSON in scala. For your particular task, here is one suggestion, assuming your JSON string has been read into the variable jsonStr:

import scala.util.parsing.json.JSON

val resultOption = JSON.parseFull(jsonStr) match {
  case Some(map: Map[String, String]) => map.get("query")
  case _ => None
}

现在,如果解析成功,则resultOption将包含SQL查询字符串,并包装在选项(否则为None).接下来,您可能应该检查错误,但是为了简单起见,如果我们盲目地假设一切工作正常,我们现在可以按以下方式访问最终值:

Now, if the parsing succeeded, resultOption will contain the SQL query string, wrapped in an option (otherwise, it will be None). Next, you should probably check for errors, but for the sake of simplicity, if we blindly assume that everything worked out nicely, we can now access the final value as follows:

val query = resultOption.get

这篇关于Scala-从包含JSON格式数据的文件中提取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆