hadoop从hdfs读取json

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

我正在尝试将一个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();
        }
    }

}

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

pxy2qtax

pxy2qtax1#

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

import pydoop.hdfs as hdfs

def lreadline(inputJsonIterator):
    with hdfs.open(inputJsonIterator,mode='rt') as f:
        lines = f.read().split('\n')
    return lines
b4lqfgs4

b4lqfgs42#

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

{"votes":[]}
{"votes":[]}

从Map器中,可以将文本对象解析为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。
否则,您必须实现 WholeFileInputFormat 把它放在工作中

job.setInputFormatClass(WholeFileInputFormat.class);

相关问题