Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Javascript dictionary to python dictionary

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?

like image 753
kk1957 Avatar asked Sep 18 '25 07:09

kk1957


1 Answers

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.

like image 162
Hoopdady Avatar answered Sep 19 '25 21:09

Hoopdady