srinigowda
srinigowda

Reputation: 70

How to Construct JSON string django view?

I want to construct json like this in the django view:

{
    "Skills": [
        {
            "Name": "Java",
            "Value": "Java"
        },
        {
            "Name": "J2ee",
            "Value": "J2ee"
        },
        {
            "Name": "Python",
            "Value": "Python"
        },
        {
            "Name": "Django",
            "Value": "Django"
        }
    ]
}

The python simplejson does not create it like the above, any suggestions please. Basically I am sending response to the select2 tag. I am invoking the view method from the Jquery ajax ..

def populateSkills(request):
    print "Inside Populate Skills"
    preload_data = '{"Skills":[{"Name":"Java","Value":"Java"},{"Name":"J2ee","Value":"J2ee"},{"Name":"Python","Value":"Python"},{"Name":"Django","Value":"Django"}]}'
    return HttpResponse(simplejson.dumps(preload_data), content_type="application/json")

I have the preload_data hard-coded as I could not construct it. So how do I construct it? is there a JSONObject to do it?

Upvotes: 0

Views: 899

Answers (1)

Lukasz Koziara
Lukasz Koziara

Reputation: 4320

Using simplejson:

import simplejson
simplejson.dumps({'Skills': [{'Name': 'Java', 'Value': 'Java'}, {'Name': 'J2ee', 'Value': 'J2ee'}, {'Name': 'Python', 'Value': 'Python'}, {'Name': 'Django', 'Value': 'Django'}] })

Upvotes: 2

Related Questions