2016-10-21 2 views
0

У меня есть jsonfile быть формат JSON parsed.The, как это:Как разобрать jsonfile с искрой

{"cv_id":"001","cv_parse": { "educations": [{"major": "English", "degree": "Bachelor" },{"major": "English", "degree": "Master "}],"basic_info": { "birthyear": "1984", "location": {"state": "New York"}}}} 

Я должен получить каждое слово в file.How я могу получить "major" из массива и мне нужно получить слово «провинция», используя метод df.select("cv_parse.basic_info.location.province")?

Это результат я хочу:

cv_id major degree birthyear state 
001 English Bachelor 1984  New York 
001 English Master  1984  New York 

ответ

0

Это может быть не лучшим способом сделать это, но вы можете дать ему шанс.

// import the implicits functions 
import org.apache.spark.sql.functions._ 
import sqlContext.implicits._ 

//read the json file 
val jsonDf = sqlContext.read.json("sample-data/sample.json") 

jsonDf.printSchema 

Ваша схема будет выглядеть так:

root 
|-- cv_id: string (nullable = true) 
|-- cv_parse: struct (nullable = true) 
| |-- basic_info: struct (nullable = true) 
| | |-- birthyear: string (nullable = true) 
| | |-- location: struct (nullable = true) 
| | | |-- state: string (nullable = true) 
| |-- educations: array (nullable = true) 
| | |-- element: struct (containsNull = true) 
| | | |-- degree: string (nullable = true) 
| | | |-- major: string (nullable = true) 

Теперь вам нужно может быть взорвать educations столбец

val explodedResult = jsonDf.select($"cv_id", explode($"cv_parse.educations"), 
     $"cv_parse.basic_info.birthyear", $"cv_parse.basic_info.location.state") 

    explodedResult.printSchema 

Теперь ваша схема будет

root 
|-- cv_id: string (nullable = true) 
|-- col: struct (nullable = true) 
| |-- degree: string (nullable = true) 
| |-- major: string (nullable = true) 
|-- birthyear: string (nullable = true) 
|-- state: string (nullable = true) 

Теперь вы можете выберите col umns

explodedResult.select("cv_id", "birthyear", "state", "col.degree", "col.major").show 

+-----+---------+--------+--------+-------+ 
|cv_id|birthyear| state| degree| major| 
+-----+---------+--------+--------+-------+ 
| 001|  1984|New York|Bachelor|English| 
| 001|  1984|New York| Master |English| 
+-----+---------+--------+--------+-------+ 
Смежные вопросы