Java Interview Practice Problem (Beginner): Extract JSON Field

  • Post last modified:September 11, 2023
  • Reading time:3 mins read

Problem

  • We have been given an input JSON file that contains questions with options for quizzes.
  • Our task is to extract these questions from JSON and return it to the list.

Input Data

  • The input file contains JSON data for the quiz as shown below.
{
    "quiz": {
        "sport": {
            "q1": {
                "question": "Which one is correct team name in NBA?",
                "options": [
                    "New York Bulls",
                    "Los Angeles Kings",
                    "Golden State Warriros",
                    "Huston Rocket"
                ],
                "answer": "Huston Rocket"
            }
        },
        ....
    }
}

Output

  • the output contains a list of questions that we extracted from json file.
[question": "Which one is correct team name in NBA?", question": "5 + 7 = ?", question": "12 - 8 = ?"]

Before jumping to the solution consider giving an attempt.

Solution

  • Sample Input Data comes from the Input file and is stored in the resources folder.
  • The first thing we need to do is to get a hold of the input file that is stored in the resources folder. We can do that using ClassLoader which provides URI.
  • Now in order to read this file we can use the Files API provided by NIO. BufferedReader provides lines() method that will get all the lines from the file.
  • Now that we have a stream of lines we filter each line by checking if the contains a question string.
  • Once we have filtered out lines that contain the string “question” then we can find the index of it as a start index for a substring.
  • for the end position, we can search for “,” since that is the ending string for the question in JSON.
  • Now that we have the start and end index we can find the substring that contains questions. Finally, we can add those questions to the list.
public static List<String> solution(String path) throws URISyntaxException, IOException {
        URI uri = ClassLoader.getSystemResource(path)
            .toURI();

        String matchingString = "question";
        String endingString = ",";

        return Files.newBufferedReader(Path.of(uri.getPath()))
            .lines()
            .filter(l -> l.contains(matchingString))
            .map(l -> l.substring(l.indexOf(matchingString), l.indexOf(endingString)))
            .toList();
    }

Code

Find all the code for this & other exercises on GitHub

Over to youWrite down your solution in the comment section for others to get back to it

Before You Leave

Other Problems List

Leave a Reply