0

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?

3
  • 1
    May you want to explain the problem in more detail. What JSON do you get? What is input? Commented Feb 22, 2013 at 9:29
  • 2
    preload_data is string, not dictionary with nested structures. So dumps() will return this string as JSON string. Commented Feb 22, 2013 at 9:46
  • 3
    i.e. you already have some data encoded as json inside preload_data string. You are trying to encode it again using dumps(). If you already have json-encoded string, you can just output it: return HttpResponse(preload_data, content_type="application/json"). Commented Feb 22, 2013 at 9:50

1 Answer 1

2

Using simplejson:

import simplejson
simplejson.dumps({'Skills': [{'Name': 'Java', 'Value': 'Java'}, {'Name': 'J2ee', 'Value': 'J2ee'}, {'Name': 'Python', 'Value': 'Python'}, {'Name': 'Django', 'Value': 'Django'}] })
Sign up to request clarification or add additional context in comments.

Comments

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.