bsky
bsky

Reputation: 20222

Can't extract data from RESTClient response

I am writing my first Groovy script, where I am calling a REST API.

I have the following call:

def client = new RESTClient( 'http://myServer:9000/api/resources/?format=json' )

That returns:

[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]

I am trying to get the field level, like this:

def level_value = client.get( path : 'msr/data/level' )

However, when I print the value of the variable obtained:

println level_value.getData()

I get the whole JSON object instead of the field:

[[msr:[[data:{"level":"OK"}]], creationDate:2017-02-14T16:44:11+0000, date:2017-02-14T16:46:39+0000, id:136]]

So, what am I doing wrong?

Upvotes: 0

Views: 1428

Answers (1)

Matias Bjarland
Matias Bjarland

Reputation: 4482

Haven't looked at the docs for RESTClient but like Tim notes you seem to have a bit of a confusion around the rest client instance vs the respons object vs the json data. Something along the lines of:

def client = new RESTClient('http://myServer:9000/api/resources/?format=json')
def response = client.get(path: 'msr/data/level')
def level = response.data[0].msr[0].data.level

might get you your value. The main point here is that client is an instance of RESTClient, response is a response object representing the http response from the server, and response.data contains the parsed json payload in the response.

You would need to experiment with the expression on the last line to pull out the 'level' value.

Upvotes: 1

Related Questions