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
?