2017-06-26 2 views
0

ich einen Eingang csv-like-Datei wie folgt aussehen:csv-like Eingabetext zu JSON-String

"2017-06-01T01:01:01Z";"{\"name\":\"aaa\",\"properties\":{"\"propA\":\"some value\",\"propB\":\"other value\"}}" 
"2017-06-01T01:01:01Z";"{\"name\":\"bbb\",\"properties\":{"\"propB\":\"some value\","\"propC\":\"some value\",\"propD\":\"other value\"}}" 

I json Zeichenfolge wie diese erhalten möchten, so dass ich Datenrahmen aus Glatt- oder JSON-String erstellen:

[{ 
    "createdTime": "...", 
    "value":{ 
    "name":"...", 
    "properties": { 
     "propA":"...", 
     "propB":"..." 
    } 
    } 
},{ 
    "createdTime": "...", 
    "value":{ 
    "name":"...", 
    "properties": { 
     "propB":"...", 
     "propC":"...", 
     "propD":"..." 
    } 
    } 
}] 

Es ist semi-strukturierte Daten. Einige Zeilen haben möglicherweise die Eigenschaft A, aber die anderen.

Wie kann ich dies in Spark mit Scalar tun?

Antwort

0

Nach was ich von Ihrer Frage verstanden habe ist, dass Sie dataframe von CSV-ähnliche Datei erstellen möchten, die Sie haben. Wenn ich es richtig bekam, ist nach dem, was Sie

val data = sc.textFile("path to your csv-like file") 
val jsonrdd = data.map(line => line.split(";")) 
    .map(array => "{\"createdTime\":"+array(0)+",\"value\":"+ array(1).replace(",\"", ",").replace("\\\"", "\"").replace("\"{", "{").replace("{\"\"", "{\"").replace("}\"", "}")+"},") 

val df = sqlContext.read.json(jsonrdd) 
df.show(false) 

tun können, sollten Sie haben dataframe als

+--------------------+----------------------------------------------+ 
|createdTime   |value           | 
+--------------------+----------------------------------------------+ 
|2017-06-01T01:01:01Z|[aaa,[some value,other value,null,null]]  | 
|2017-06-01T01:01:01Z|[bbb,[null,some value,some value,other value]]| 
+--------------------+----------------------------------------------+ 

Above dataframe'sschema wäre

root 
|-- createdTime: string (nullable = true) 
|-- value: struct (nullable = true) 
| |-- name: string (nullable = true) 
| |-- properties: struct (nullable = true) 
| | |-- propA: string (nullable = true) 
| | |-- propB: string (nullable = true) 
| | |-- propC: string (nullable = true) 
| | |-- propD: string (nullable = true) 
Verwandte Themen