Sai Krishna
Sai Krishna

Reputation: 8187

How do I access JSON data passed via AJAX in my django application?

{
   "data": [
      {
         "name": "Kill Bill",
         "category": "Movie",
         "id": "179403312117362",
         "created_time": "2011-06-21T17:40:15+0000"
      },
      {
         "name": "In Search of a Midnight Kiss",
         "category": "Movie",
         "id": "105514816149992",
         "created_time": "2011-03-21T03:59:21+0000"
      },
      ]
}

We could use this as sample data. So if you were to extract "In Search of a Midnight Kiss" from the request.POST variable, how would you do it ?

Upvotes: 1

Views: 274

Answers (2)

Manuel Salvadores
Manuel Salvadores

Reputation: 16525

It'll come as a string that needs to be desearialized.

import json

def some_http_call(request)
   json_string = request.GET.get('http_parameter_key', '')
   json_object = json.loads(json_string)

   data = json_object["data"]
   for x in data:
       print x["name"]

Assuming some_http_call is your dispatcher and http_parameter_key is the name of the parameter where the json string is coming the code above will print all the names in the array of elements contained in the dictionary data.

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798456

First you deserialize it using simplejson or json, then you access it as you would any other Python object.

Upvotes: 1

Related Questions