0

I have a groovy code in which a python script is invoked. Is there a way to read the json serialized data printed/returned by the python script?

Groovy code to call python script:

def sout = new StringBuilder(), serr = new StringBuilder()
def cmd = ["python2.7","myscript.py"]
def proc = cmd.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitFor()
def parser = new JsonSlurper()
def jsonResp = parser.parseText(sout[0])
log.debug(jsonResp)

Python script:

dd = {'key1': 'value1', 
      'key2':'value2', 
      'key3': {'key31':'value31'}
      }
print json.dumps(dd)

Output:

jsonResp = {} when the code is run.

jsonResp['key1'] also is empty implying that json is not read from process output.

Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30
minzey
  • 116
  • 2
  • 11

1 Answers1

0

You may be looking for this:

  • print json.drumps(dd) from the python code works well and completed its work. you have to read the process output inside the groovy code correctly.

In groovy script, def jsonResp = parser.parseText(sout[0]) you are using java.lang.StringBuilder as Array list. This will act like String []. So you are loading first character "{" of your string sout[0]in total String.

I don't know why you put it like this.

JsonSlurper().parseText only allows the String argument See doc. You can use it like below shown ways:

  • parseText(sout.toString())

  • parseText(sout.readLines())

Bhanuchander Udhayakumar
  • 1,581
  • 1
  • 12
  • 30