4

Somewhere in my Django app, I make an Ajax call to my view

$.post("/metrics", {
  'program': 'AWebsite',
  'marketplace': 'Japan',
  'metrics': {'pageLoadTime': '1024'}
});

in my python code, I have got

@require_POST
def metrics(request):
    program = request.POST.get('program', '')
    marketplace = request.POST.get('marketplace', '')
    metrics = request.POST.get('metrics', '')
    reportMetrics(metrics, program, marketplace)

the metrics() function in python is supposed to call reportMetrics() with these parameters which are then supposed to go in a log file. But In my log file, I do not see the 'pageLoadTime' value - probably because it is being passed in as a dictionary. In future I need to add more items to this, so it needs to remain a dictionary (and not a string like first two).

Whats the easiest way to convert this incoming javascript dictionary to python dictionary?

1 Answer 1

7

Send the javascript dictionary as json and import the python json module to pull it back out. You'll use json.loads(jsonString).

Edit - Added example

$.post("/metrics", {
   data: JSON.stringify({
      'program': 'AWebsite',
      'marketplace': 'Japan',
      'metrics': {'pageLoadTime': '1024'}
   })
});

Then on the python side

import json
def metrics(request):
    data = json.loads(request.POST.get('data'))
    program = data.get('program','')
    marketplace = data.get('marketplace','')
    metrics = data.get('metrics','')

I don't really have a good way of testing this right now, but I believe it should work. You may also have to do some checking if a field is blank, but I believe .get() will handle that for you.

Sign up to request clarification or add additional context in comments.

4 Comments

u mean instead of 'metrics': {'pageLoadTime': '1024'} , do 'metrics': '{pageLoadTime: 1024}' and then json.loads() ?
its been awhile but believe you can just do $.post("/metrics", {data:JSON.stringify({'program':'Awebsite', ...})}) and access everything thing through data in python.
sorry, I think I am not getting it. Can you show how to extract in python with code example?
I added the python to the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.