Splunk® Enterprise

Module System User Manual

Acrobat logo Download manual as PDF


Splunk Enterprise version 7.1 is no longer supported as of October 31, 2020. See the Splunk Software Support Policy for details. For information about upgrading to a supported version, see How to upgrade Splunk Enterprise.
This documentation does not apply to the most recent version of Splunk® Enterprise. For documentation on the most recent version, go to the latest release.
Acrobat logo Download topic as PDF

Render JSON data

Important notice: As part of Advanced XML deprecation, the Module System is officially deprecated beginning with Splunk Enterprise 6.3. For more information, see Advanced XML Deprecation.

To add your module code
To define the CustomJSONResults module
To handle the search request, returning JSON-formatted data
To render the JSON data
To integrate the CustomJSONResults module into the app view


SplunkIcon.pngExample 5


This recipe is the same as the Create a custom module recipe, except that results are formatted as JSON and sent to the client for rendering, instead of raw HTML.

Details

The main point of interest is the introduction of the render_json() method to transmit JSON-formatted data to the client. We also get the CPU utilization dataset directly, using the field name, instead of implicitly as in the CustomResultsTable module.

 

This represents an intermediate step between rendering an HTML table and a visualization that requires JSON, which we'll demonstrate in the Include 3rd-party libraries recipe.

To add your module code

Create the $SPLUNK_HOME/etc/apps/splunk_app_framework_documentation/appserver/modules/CustomJSONResults directory and add the following files:

  • CustomJSONResults.conf
  • CustomJSONResults.js
  • CustomJSONResults.py

To define the CustomJSONResults module

In your CustomJSONResults.conf file, set the module class name and specify the base class from which it inherits.

[module] className = Splunk.Module.CustomJSONResults superClass = Splunk.Module.DispatchingModule

In this example, Splunk.Module.CustomJSONResults inherits from Splunk.Module.DispatchingModule, which itself inherits from the root module class, Splunk.Module.

The module has no static parameters so none are defined.

To handle the search request, returning JSON-formatted data

The CustomJSONResults.py file implements server-side request handling. It simply formats the response data for the module and transmits it to the client.

  1. Import the libraries needed for working with JSON, including the CherryPy framework component for setting the content type in the response header.

    import cherrypy import jsonfrom splunk.appserver.mrsparkle.lib import jsonresponse

  2. Import libraries needed by most modules.

    import controllers.module as module import splunk import splunk.search import splunk.util import splunk.entity import lib.util as util import lib.i18n as i18n import logging

    logger = logging.getLogger('splunk.module.CustomJSONResults')

  3. Define the class, inheriting from ModuleHandler.

    class CustomJSONResults(module.ModuleHandler)

  4. Override the generateResults() method to implement the code specific to this module.

    def generateResults(self, host_app, client_app, sid, count=1000,

       offset=0, entity_name='results'):
    

    The sid, count, offset, and entity_name parameters are used to locate the data associated with the search request.

    count = max(int(count), 0) offset = max(int(offset), 0) if not sid:

       raise Exception('CustomJSONResults.generateResults - sid not passed!')
    

    Use the job ID parameter, sid, to get the associated job for retrieving results data.

    try:

       job = splunk.search.getJob(sid)
    

    except splunk.ResourceNotFound, e:

       logger.error('CustomJSONResults could not find the job %s. Exception: %s' % (sid, e))
    

    return _('<p class="resultStatusMessage">Could not retrieve search data.</p>')

    Get the results data for the associated job.

    dataset = getattr(job, entity_name)[offset: offset+count]

    Iterate through the results, using the indexer name and totalCPU literals, appending the name-value pairs to the outputJSON dictionary.

    outputJSON = {} for i, result in enumerate(dataset):

       outputJSON[str(result.get('name', None))] = str(result.get('totalCPU', None))
    

    Use the CherryPy utility to set the text/json content type in the response header, and transmit the JSON string to the client using the json.dumps() method.

    cherrypy.response.headers['Content-Type'] = 'text/json' return json.dumps(outputJSON, sort_keys=True)

    Note: Beginning with release 4.x, you can use render_json() to transmit JSON data.

    The generateResults() method formats CPU utilization data similar to the following JSON example:

    {

       dev-null":"0.000000",
       fschangemanager":"0.000000",
       indexerpipe":"9.327396",
       merging":"0.543903",
       parsing":"0.031909",
       scheduler":"0.000000",
       tcp":"0.000000",
       typing":"0.120027"
    

    }

To render the JSON data

Client-side code is implemented in the CustomJSONResults.js file.

Note: Refer to the Create a custom module example for the general discussion of client processing. Here, we primarily cover the renderRusults() method, which is the major change from the previous example.

  1. Client-side code is implemented in the CustomJSONResults.js file, which renders the JSON data.

    Define the client component by subclassing Splunk.Module.DispatchingModule.

    Splunk.Module.CustomJSONResults = $.klass(Splunk.Module.DispatchingModule, {...}

  2. Override the renderResults() method to render the JSON data in the module container.

    Validate that data is actually available from the server:

    renderResults: function($super, results) {

       if(!results) {
           this.resultsContainer.html('No content available.');
           return;
    

    }

    The main function of the method is to build the HTML fragment, which is similar to what was done by the server in the Create a custom module example:

    htmlFragment = '<div class="CustomResultsTableWrapper">'; htmlFragment += '<table class="CustomResultsTable splTable">'; for (var key in results) {

       htmlFragment += '<tr>';
       htmlFragment += '<td>' + key  + '</td><td>' + results[key]  + '</td>';
       htmlFragment += '</tr>';
    

    } htmlFragment += '</table></div>'; this.resultsContainer.html(htmlFragment); }

Iterating through the keys in the JSON name-value pairs, the code builds the table, which is rendered by calling the html() method of resultsContainer, passing the HTML fragment as a parameter and using the jQuery appendTo() method to insert the fragment into the target container.

To integrate the CustomJSONResults module into the app view

In the $SPLUNK_HOME/etc/apps/splunk_app_framework_documentation/default/data/ui/views/Example5.xml file, add the following line in the view hierarchy where you want your module data rendered:

<module name="CustomJSONResults"></module>

The HTML table is rendered in the bottom-most panel, displaying search results initiated by the HiddenSearch module and forwarded to the CustomJSONResults module.

Related recipes

Create a custom module shows you the basics of creating a custom module.

Include 3rd-party libraries shows you how to import third-party graphics library for more advanced rendering.

Parameterize your module shows you how to statically parameterize your module.

Setup your app shows you how to make your app configurable.

Last modified on 12 August, 2019
PREVIOUS
Example 4 - Create a custom module
  NEXT
Example 6 - Include 3rd-party libraries

This documentation applies to the following versions of Splunk® Enterprise: 7.0.0, 7.0.1, 7.0.2, 7.0.3, 7.0.4, 7.0.5, 7.0.6, 7.0.7, 7.0.8, 7.0.9, 7.0.10, 7.0.11, 7.0.13, 7.1.0, 7.1.1, 7.1.2, 7.1.3, 7.1.4, 7.1.5, 7.1.6, 7.1.7, 7.1.8, 7.1.9, 7.1.10, 7.2.0, 7.2.1, 7.2.2, 7.2.3, 7.2.4, 7.2.5, 7.2.6, 7.2.7, 7.2.8, 7.2.9, 7.2.10, 7.3.0, 7.3.1, 7.3.2, 7.3.3, 7.3.4, 7.3.5, 7.3.6, 7.3.7, 7.3.8, 7.3.9


Was this documentation topic helpful?


You must be logged into splunk.com in order to post comments. Log in now.

Please try to keep this discussion focused on the content covered in this documentation topic. If you have a more general question about Splunk functionality or are experiencing a difficulty with Splunk, consider posting a question to Splunkbase Answers.

0 out of 1000 Characters