cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
7063
Views
2
Helpful
5
Comments
rwhitear42
Cisco Employee
Cisco Employee

This document partners the document ‘Generating JSON Data Within UCS Director Custom Workflow Tasks’ which can be found here:

https://communities.cisco.com/docs/DOC-58185

However, rather than creating JSON objects from Java HashMaps, this document describes how to parse JSON strings within UCS Director.

For this exercise, we will use the same JSON string that we created in the previous document:

{

    "pool":"test-http-pool",

    "description":"My test virtual server",

    "name":"test-http-virtual",

    "mask":"255.255.255.255",

    "profiles":[

        {

            "name":"http",

            "kind":"ltm:virtual:profile"

        },

        {

            "name":"tcp",

            "kind":"ltm:virtual:profile"

        }

    ],

    "ipProtocol":"tcp",

    "sourceAddressTranslation":{"type":"automap"},

    "kind":"tm:ltm:virtual:virtualstate",

    "destination":"1.1.1.3:80"

}

Also, this document will demonstrate how to verify the existence of the element being requested. It will also demonstrate how to test whether the element is a JSON object or a JSON array. In the event of an array, it will also demonstrate how to retrieve the array length.

So, let’s get started.

Once again, we need to  access the JSON parsing functionality within UCS Director,  and therefore need to start our CloupiaScript with the following:

importPackage(com.cloupia.lib.util);

Next, we’ll configure a variable with the JSON string example shown at the start of this document:

var jsonData = '{"pool":"test-http-pool","description":"My test virtual server","name":"test-http-virtual","mask":"255.255.255.255","profiles":[{"name":"http","kind":"ltm:virtual:profile"},{"name":"tcp","kind":"ltm:virtual:profile"}],"ipProtocol":"tcp","sourceAddressTranslation":{"type":"automap"},"kind":"tm:ltm:virtual:virtualstate","destination":"1.1.1.3:80"}';

The next step is to consume this string as a JSON object:

var data = JSON.getJsonElement(jsonData,null);

In this case, jsonData is the JSON string that we are looking to parse, and null simply means to parse the entire string. Had we just wanted to retrieve the ‘profiles’ element, then the request would look like so:

var data = JSON.getJsonElement(jsonData, "profiles");

Screen Shot 2015-05-12 at 16.40.07.png

When incorporating conditional branching and validation within custom workflow tasks, it is desirable to ascertain ahead of time information about the JSON object or array that is being retrieved. Below are various validation requests that can be performed upon the JSON string.

Once we have set a variable as a JSON element, the following methods can be used:

isJsonObject() – Returns boolean true if element is a JSON object.

isJsonArray() – Returns boolean true if element is a JSON array.

isString() – Returns boolean true if element is a String.

isNumber() – Returns boolean true if element is a number.

isBoolean() – Returns boolean true if element is a boolean.

isJsonNull() - Returns boolean true if element is Null.

The following commands, run within UCS Director’s CloupiaScript Interpreter demonstrate the above methods:

Screen Shot 2015-05-12 at 16.41.23.png

Existence of a specific key can be checked programmatically with the has() method.

data.has("pool");

true

Screen Shot 2015-05-12 at 16.42.35.png

Also, when the element is a JSON array, it is possible to ascertain the length of the array in order to programmatically iterate through it. Once the element has been determined to be a JSON array, the size() method can be used to find the length of the array.

var data = JSON.getJsonElement(jsonData, "profiles");

[{"name":"http","kind":"ltm:virtual:profile"},{"name":"tcp","kind":"ltm:virtual:profile"}]

data.isJsonArray();

true

data.size();

2

Screen Shot 2015-05-12 at 16.44.42.png

Once the array size is ascertained, the individual array elements can be retrieved with the get() method.

data.get(0); // 0 is index zero of the array.

{"name":"http","kind":"ltm:virtual:profile"}

data.get(1); // 1 is index one of the array.

{"name":"tcp","kind":"ltm:virtual:profile"}

You now have all the tools required to retrieve any JSON element.

var data = JSON.getJsonElement(jsonData,null);

data.get("profiles").get(0).get("name");

data.get("profiles").get(0).get("kind");

Screen Shot 2015-05-12 at 16.47.00.png

Finally, the retrieved elements are still JSON objects. The getAsString() method can be used in order to retrieve the JSON element as a String:

var data = JSON.getJsonElement(jsonData,null);

var str = data.get("pool");

str.length();

sun.org.mozilla.javascript.internal.EcmaError: TypeError: Cannot find function length. (<Unknown source>#1) in <Unknown source> at line number 1

str = data.get("pool").getAsString();

test-http-pool

str.length();

14

Comments
wellsgzhk
Cisco Employee
Cisco Employee

Very helpful explanation on how to manipulate JSON data with Cloupia script.

gene.williams
Level 1
Level 1

Anybody ever had a problem with (what seems like) a JSON response being truncated?  -possibly due to size, the output of the truncated JSON in the SR log is 65,518 characters long.  The complete response from the same request when run from curl is 402,282 characters.

My custom task has this:

        var request = createGetCall(apiServer, apiUser, apiPassword, uriPath);

        response = executeRequest(request);

        var data = JSON.getJsonElement(response,null);

From SR Log (first line here is the end of the large JSON response, my guess is that the error is due to the JSON not being complete):

system.customfieldtypes:datepicker','customId':15013}},{'id':'customfield_15014','name':'Implementer',

May 10, 2018 22:07:50 UTC Error occured at line # 151

May 10, 2018 22:07:50 UTC [Line#151]         var data = JSON.getJsonElement(response,null);

May 10, 2018 22:07:50 UTC Task: Get Jira_Details (custom_Jira_Get_Details) failed with error - com.google.gson.stream.MalformedJsonException: invalid number or unquoted string near  in <eval> at line number 151, selectedContext=<None>

gene.williams
Level 1
Level 1

I’m still curious about the size limitation, but trying to work around this problem by hardcoding some known fields, I hit the same error, so

1. The prior apparent truncation *might* only be in the SR log and not in the variable.

2. I have an unknown issue with JSON.getJsonElement()

This time, I sent an element name as demonstrated in https://communities.cisco.com/docs/DOC-58243, like this:

     var data = JSON.getJsonElement( response, 'fields' );

Here’s the log snippet:

May 11, 2018 18:13:10 UTC stringResponse = {'expand':'renderedFields,names,schema,operations,editmeta,changelog,versionedRepresentations','id':'78523','self':'https://jiratest.ercot.com/rest/api/latest/issue/78523','key':'ITCMB-6422','fields':{'customfield_16903':'itw0248','customfield_12946':{'self':'https://jiratest.ercot.com/rest/api/2/customFieldOption/11626','value':'Windows','id':'11626'},'customfield_13609':null}}

May 11, 2018 18:13:10 UTC Error occured at line # 145

May 11, 2018 18:13:10 UTC [Line#145] var data = JSON.getJsonElement( response, 'fields' );

May 11, 2018 18:13:10 UTC Task: Get Jira_Details (custom_Jira_Get_Details) failed with error - com.google.gson.stream.MalformedJsonException: invalid number or unquoted string near  in <eval> at line number 145, selectedContext=<None>

Any ideas?

Thanks,

Gene

gene.williams
Level 1
Level 1

(when I paste the JSON from the SR log into a JSON validator, it fails, but only because of the SR log's conversion of double quotes to single quotes.  Converting all single quotes to double to match the actual input into JSON.getJsonElement(), the JSON is valid).

Orf Gelbrich
Cisco Employee
Cisco Employee

I am sure there is aluminum in ucsd if 64k since every thing ends unpin a field in a dB

Getting Started

Find answers to your questions by entering keywords or phrases in the Search bar above. New here? Use these resources to familiarize yourself with the community:

Quick Links

Review Cisco Networking for a $25 gift card