-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathSimple_Json_Parser
More file actions
88 lines (61 loc) · 3.73 KB
/
Copy pathSimple_Json_Parser
File metadata and controls
88 lines (61 loc) · 3.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
/**
* Created by divesh.pathak on 11/3/2015.
* Just learning spark and feel there is issue in parsing json file for the begineers so written a simple program
* Take the json input file in the format given here.
* {"age":100,"name":"Divesh","messages":["msg 1","msg 2","msg 3"]}
* The program will take one line of json as one record.
*/
import org.apache.spark.SparkConf;
import org.apache.spark.api.java.JavaRDD;
import org.apache.spark.api.java.JavaSparkContext;
import org.apache.spark.api.java.function.FlatMapFunction;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
public class Simple_Json_Parser implements Serializable {
static ArrayList<String> text1 = new ArrayList<String>();
public static void main(String[] argsc){
SparkConf sparkConf=new SparkConf().setAppName("MYApp_Json_Parser").setMaster("local[1]");
JavaSparkContext ctx=new JavaSparkContext(sparkConf);
JavaRDD<String> lines=ctx.textFile("C:\\Data\\Test.json", 1);
JavaRDD<String> words=lines.flatMap(new FlatMapFunction<String, String>(){
public Iterable<String> call(String s){
String Message = "";
try {
JSONParser parser = new JSONParser();
Object obj = parser.parse(s);
JSONObject jsonObject = (org.json.simple.JSONObject) obj;
String name = (String) jsonObject.get("name");
//System.out.print(name + ",");
long age = (Long) jsonObject.get("age");
//System.out.print(age + ",");
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
//System.out.print(iterator.next() + ",");
Message =Message+iterator.next()+"," ;
}
// System.out.print(Message);
// System.out.println();
String a = name+","+ String.valueOf(age)+","+Message;
Object obj1= a;
text1.add(a);
} catch (ParseException e1) {
e1.printStackTrace();
}
return text1;
}
}
);
// Iterable<Object> iterable = text1;
System.out.println( words.count());
String outfile = "C:\\Data\\Test";
JavaRDD list = ctx.parallelize(text1);
list.saveAsTextFile(outfile);
ctx.stop();
}
}