hadoop从hdfs读取json

3phpmpom  于 2021-05-27  发布在  Hadoop
关注(0)|答案(2)|浏览(681)

我正在尝试将一个json文件读入hadoop mapreduce算法。我该怎么做?我已经将文件“testinput.json”放入hdfs内存的/input中。
调用mapreduce时我执行 hadoop jar popularityMR2.jar populariy input output ,输入说明dhfs内存中的输入目录。

  1. public static class PopularityMapper extends Mapper<Object, Text, Text, Text>{
  2. protected void map(Object key, Text value,
  3. Context context)
  4. throws IOException, InterruptedException {
  5. JSONParser jsonParser = new JSONParser();
  6. try {
  7. JSONObject jsonobject = (JSONObject) jsonParser.parse(new FileReader("hdfs://input/testinput.json"));
  8. JSONArray jsonArray = (JSONArray) jsonobject.get("votes");
  9. Iterator<JSONObject> iterator = jsonArray.iterator();
  10. while(iterator.hasNext()) {
  11. JSONObject obj = iterator.next();
  12. String song_id_rave_id = (String) obj.get("song_ID") + "," + (String) obj.get("rave_ID")+ ",";
  13. String preference = (String) obj.get("preference");
  14. System.out.println(song_id_rave_id + "||" + preference);
  15. context.write(new Text(song_id_rave_id), new Text(preference));
  16. }
  17. }catch(ParseException e) {
  18. e.printStackTrace();
  19. }
  20. }
  21. }

我的Map器函数现在看起来像这样。我从dhfs内存中读取了文件。但它总是返回一个错误,文件找不到。
有人知道如何将这个json读入jsonobject吗?
谢谢

pxy2qtax

pxy2qtax1#

尝试使用pydoop库使用以下函数从hdfs路径读取json,结果一切正常。希望对您有所帮助。

  1. import pydoop.hdfs as hdfs
  2. def lreadline(inputJsonIterator):
  3. with hdfs.open(inputJsonIterator,mode='rt') as f:
  4. lines = f.read().split('\n')
  5. return lines
b4lqfgs4

b4lqfgs42#

FileReader 无法读取hdfs,只能读取本地文件系统。
文件路径来自作业参数- FileInputFormat.addInputPath(job, new Path(args[0])); 无论如何,你不会在mapper类中读取文件。
mapreduce默认读取行分隔的文件,因此json对象必须是每行一个,例如

  1. {"votes":[]}
  2. {"votes":[]}

从Map器中,可以将文本对象解析为jsonobject,如下所示

  1. protected void map(LongWritable key, Text value, Context context)
  2. throws IOException, InterruptedException {
  3. JSONParser jsonParser = new JSONParser();
  4. try {
  5. JSONObject jsonobject = (JSONObject) jsonParser.parse(value.toString());
  6. JSONArray jsonArray = (JSONArray) jsonobject.get("votes");

如果文件中只有一个json对象,那么可能不应该使用mapreduce。
否则,您必须实现 WholeFileInputFormat 把它放在工作中

  1. job.setInputFormatClass(WholeFileInputFormat.class);
展开查看全部

相关问题