0

Context:

I'm using the nexus scripting API to return some data. For some reason, returned data isn't JSON compliant. I am on nexus PRO 3.20.1-01. I'm not sure if this is a problem with Nexus or my script.

Here is a testable Groovy sample, deployable on nexus (the script is called testScript.groovy)

import groovy.json.JsonOutput;

Map listOfValues = new HashMap<>();
HashSet<String> values = new HashSet<String>();
values.add('test1');
values.add('test2');
values.add('test3');

listOfValues.put('someValues',values);

Map<String, String> keyValues = new HashMap<>();
keyValues.put('firstKey','firstKey');
keyValues.put('secondKey','secondValue');

listOfValues.put('keyValues',keyValues);

result = JsonOutput.toJson(listOfValues);
return result;

(I know I don't need ; in Groovy, but I can't do otherwise for the moment)

And I'm calling it with:

result=$(curl --noproxy $NO_PROXY --insecure -u $NEXUS_USERNAME:$NEXUS_PASSWORD -X POST --header 'Content-Type: application/json' $NEXUS_SCRIPT_ENDPOINT/test/run)
echo 'result:'
echo $result

And the result (content of the http response) is:

result: { "name" : "testScript", "result" : "{\"keyValues\":{\"firstKey\":\"firstKey\",\"secondKey\":\"secondValue\"},\"someValues\":[\"test2\",\"test3\",\"test1\"]}" }


Problem:

There is 2 problems with this response:

First, all the escaped doubles quotes \" which makes this response non JSON compliant. I can still use printf "$result" to get rid of them. So the result would be: result:

{
  "name" : "test",
  "result" : "{"keyValues":{"firstKey":"firstKey","secondKey":"secondValue"},"someValues":["test2","test3","test1"]}"
}

Second, the value of result is always quoted, see "result" : "{...}" where it should be "result" : {...}. Which makes it not JSON compliant. It seems that the returned value is always interpreted as a Java/Groovy String. So I can't parse the html content as a JSON and do result.keyValues.firstKey for instance.

Question:

Is there anyway to make the returned html response a valid JSON where I can parse the result ?

Asoub
  • 2,273
  • 1
  • 20
  • 33

1 Answers1

1

You are putting an JSON encoded String inside JSON - so the output is expected and of course is valid JSON.

If whatever deals with your result from groovy is not able to JSON encode it itself (e.g. return listOfValues instead of result), you have to live with the response you get. Decode the response once and then decode response.result again.

cfrick
  • 35,203
  • 6
  • 56
  • 68
  • Ah yes, JsonOutput.toJson does return a String .... I've tried to return listOfValues, but result now contains the toString() of the map, which is even worse. I'll wait a litlle to see if someone has another solution, but I guess I'll have to parse the result. – Asoub Feb 11 '20 at 14:26