tabdon
tabdon

Reputation: 157

Using jQuery to Read a JSON File Generated by Django's Serialization

I'm successfully generating a JSON object using Django Serialization. I do so with this view:

def fetch_content(request, content_id):

content = serializers.serialize('json', [ContentQueue.objects.get(id=content_id)], fields=('title', 'description'))
mimetype = 'application/javascript; charset=utf8'

return HttpResponse(content, mimetype)

This spits out JSON like this:

[{"pk": 24, "model": "contentqueue", "fields": {"description": "Aerosmith frontman Steven Tyler was typically gabby...", "title": "Steven Tyler Tells All: On The Cover of Rolling Stone"}}]

I'm trying to read this JSON file with the below jQuery code:

api_url = /fetch-content/ + content_id;
$.getJSON(api_url, function(json) {
    var type = json.title;
    var desc = json.description;
    <then I display the content onscreen>

I've tried accessing the content by json.fields.title but that doesn't work. What am I doing wrong?

Upvotes: 1

Views: 399

Answers (1)

Kevin Ennis
Kevin Ennis

Reputation: 14464

var type = json[0].fields.title

You first have to define the array index. Other than that, you're on the right track.

Upvotes: 2

Related Questions