0

Quick backstory- I am building a Java web app using MVC structure and Spring Framework. My controller object calls a Python script that queries a bunch of APIs and returns a JSON payload that I would like to capture and work with in my Java file.

After aggregating information from a few different sources, here is what I have so far:

        String currQuery = "cmd /c python ../../../../python/state/main.py";
        Process p = Runtime.getRuntime().exec(currQuery);
        p.waitFor();

        BufferedReader stdInput = new BufferedReader(new
                InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new
                InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

As you can see this would print each line of the return value the script. However, what I want is to be able to interact with the JSON object returned by main.py within my Java class.

What is the best way to pass a JSON object between the python file being executed and my Java class?

Perhaps using JSONReader? Any advice/ suggestions would be greatly appreciated and let me know if more information is needed.

maksimov
  • 5,792
  • 1
  • 30
  • 38
skhan
  • 199
  • 10
  • Python script is an unnecessary detail here. Your question is about reading (parsing) JSON in Java. Take a look at a similar question and the best answer: https://stackoverflow.com/a/18998203/211197 – maksimov Jul 24 '19 at 20:01
  • why do you have to run a python script? why not make the requests using java – Toerktumlare Jul 24 '19 at 20:05
  • @maksimov im slightly confused about actually linking the output of the python script to my java file- is using the Process class and reading in the stdIn the best way to begin parsing the JSON or is there an easier way to access/ interact with the output of executing a py script? thanks – skhan Jul 24 '19 at 20:22
  • @ThomasAndolf theres some more stuff happening in the python scripts where implementing pandas, etc. is the simplest way to achieve my goal but its irrelevant to the problem at hand so I didnt expand on it in my question – skhan Jul 24 '19 at 20:24
  • 2
    @shadkhan I'm not sure if you have a lot of options here. It is true that it is quite an unusual mix of technologies: there is nothing in Python that you couldn't do in Java, and vice versa: nothing in Java that you couldn't just do in Python. Generally people tend to stick to fewer languages in a single project for maintainability reasons. If it's a legacy situation where you must use Python script and must interact with it from Java then your approach of reading the script output is quite sound. – maksimov Jul 24 '19 at 20:34

0 Answers0