Splunk Dev

How to read Ajax passed JSON object in Python?

kasu_praveen
Communicator

Hi,

How to read Ajax passed JSON object in .py file? Below are my code snippets from Splunk view, web.conf and .py file.
Looking for code snippet in How to read Ajax passed JSON object here????? section of my .py file

JavaScript:

var dataVal = {'JSONObjKey': JSONObject,'SimpleString': 'String1'};
var JsonData = JSON.stringify(dataVal);
function callScript(){
             $.ajax({
                   type: "POST",
                   url: "/custom/MyApp/my_script/my_endpoint",
                   data: JsonData,
                   contentType: "application/json; charset=utf-8",
                   dataType: "json",
                   success: function(data) {
                       console.log("success returned");
                       console.log(data);
                   },
                   error: function(xhr){
            console.log("Error");
                }
             });
         }        
         callScript();

web.conf

[endpoint:my_script]

my_script.py

import logging
import cherrypy
import splunk.appserver.mrsparkle.controllers as controllers
from splunk.appserver.mrsparkle.lib.util import make_splunkhome_path
from splunk.appserver.mrsparkle.lib.decorators import expose_page

 _APPNAME = 'MyApp'
 def setup_logger(level):
  logger = logging.getLogger('splunk.appserver.%s.controllers.my_script' % _APPNAME)
  logger.propagate = False  # Prevent the log messages from being duplicated in the python.log file
  logger.setLevel(level)
  file_handler = logging.handlers.RotatingFileHandler(
      make_splunkhome_path(['var', 'log', 'splunk', 'my_script_controller.log']), maxBytes=25000000, backupCount=5)
  formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
  file_handler.setFormatter(formatter)
  logger.addHandler(file_handler)
  return logger
 logger = setup_logger(logging.DEBUG)

 class my_script(controllers.BaseController):
  @expose_page(must_login=True, methods=['POST'])
  def my_endpoint(self, **kwargs):
   cherrypy.response.headers['Content-Type'] = 'application/json'
 <<<<<<How to read ajax passed JSON object here?????>>>>>>>
 <<<<<<kwargs['JSONObjKey'] doesn't work here>>>>>>>
   return "Return JSON Object data here????"
0 Karma

jkat54
SplunkTrust
SplunkTrust

in python you will want to import json for handling json.

Here's how to use the json library: https://docs.python.org/2/library/json.html

I would not use cherrypy here though. cherrypy is deprecated in Splunk.

GIve this a read: https://conf.splunk.com/files/2016/slides/extending-splunks-rest-api-for-fun-and-profit.pdf

and refer to the github link at the end of the presentation for sample code.

0 Karma
Get Updates on the Splunk Community!

Fueling your curiosity with new Splunk ILT and eLearning courses

At Splunk Education, we’re driven by curiosity—both ours and yours! That’s why we’re committed to delivering ...

Splunk AI Assistant for SPL 1.1.0 | Now Personalized to Your Environment for Greater ...

Splunk AI Assistant for SPL has transformed how users interact with Splunk, making it easier than ever to ...

Unleash Unified Security and Observability with Splunk Cloud Platform

     Now Available on Microsoft AzureOn Demand Now Step boldly into the AI revolution with enhanced security ...