我正在尝试将JSON文件读取到我的hadoop mapreduce算法中。我怎样才能做到这一点?我已将文件'testinput.json'放入HDFS内存中的/ input中。
[当调用mapreduce时,我执行hadoop jar popularityMR2.jar populariy input output
,输入内容指明dhfs存储器中的输入目录。
public static class PopularityMapper extends Mapper<Object, Text, Text, Text>{
protected void map(Object key, Text value,
Context context)
throws IOException, InterruptedException {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonobject = (JSONObject) jsonParser.parse(new FileReader("hdfs://input/testinput.json"));
JSONArray jsonArray = (JSONArray) jsonobject.get("votes");
Iterator<JSONObject> iterator = jsonArray.iterator();
while(iterator.hasNext()) {
JSONObject obj = iterator.next();
String song_id_rave_id = (String) obj.get("song_ID") + "," + (String) obj.get("rave_ID")+ ",";
String preference = (String) obj.get("preference");
System.out.println(song_id_rave_id + "||" + preference);
context.write(new Text(song_id_rave_id), new Text(preference));
}
}catch(ParseException e) {
e.printStackTrace();
}
}
}
我的映射器功能现在看起来像这样。我从dhfs内存中读取了文件。但是它总是返回错误,找不到文件。
有人知道我如何将这个json读入jsonobject吗?
谢谢
FileReader
无法从HDFS读取,只能从本地文件系统读取。
文件路径来自Job参数-FileInputFormat.addInputPath(job, new Path(args[0]));
无论如何,您将不会在Mapper类中读取文件。
MapReduce默认读取行分隔文件,因此您的JSON对象必须是每行一个,例如
{"votes":[]}
{"votes":[]}
从映射器中,您将像这样将Text对象解析为JSONObject
protected void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
JSONParser jsonParser = new JSONParser();
try {
JSONObject jsonobject = (JSONObject) jsonParser.parse(value.toString());
JSONArray jsonArray = (JSONArray) jsonobject.get("votes");
如果文件中只有一个JSON对象,则可能不应该使用MapReduce。