简体   繁体   中英

Problems with Django and Parsing a json

I am trying to take a posted json, and import the object into the django database.
The Json looks like:

{
"pooledSets" : [
    {
        "name" : "Pooled Set 1",
        "madeBy" : "John Doe",
        "tags" : ['thing1','thing2' ],
        "sets" : [
            {
                "library" : {
                "replicate" : 2,
                "name" : "My library name",
                "referenceGenome" : "hg19-male"
            }
        ]
    },
            {
        "name" : "Pooled Set 1",
        "madeBy" : "John Doe",
        "tags" : ['thing1','thing2' ],
        "sets" : [
            {
                "library" : {
                "replicate" : 2,
                "name" : "My library name",
                "referenceGenome" : "hg19-male"
            }
        ]
    }
]
}

And my code looks like:

import json
from django.http import HttpResponse
from piston.handler import BaseHandler
from lab.pooledsets.models import PooledSet
from django.http import QueryDict

class PooledSetJsonHandler(BaseHandler):
    allowed_methods = ('POST')

    def create(self, request):          
        for myPooledSet in request.POST.getlist('pooledSets'):
            myDict = QueryDict(myPooledSet, 'json')
            print myDict
            myName = myDict.__getitem__('name')
            print myName

When run, myDict comes out just fine:

<QueryDict: {u"{u'name': u'Pooled Set 1', u'tags': [u\'thing1\', u\'thing2\'], u'sets': etc etc etc

However I get the error:

File "/api/pooled_set_post.py", line 17, in create
myName = myDict.__getitem__('name')

File "/Library/Python/2.6/site-packages/django/utils/datastructures.py", line 258, in __getitem__
raise MultiValueDictKeyError("Key %r not found in %r" % (key, self))

What happened, and how do I go about extracting the key value pairs?

Your dict is not coming out fine. Look at it:

{u"{u'name': u'Pooled Set 1', u'tags': [u\'thing1\', u\'thing2\'], u'sets': …}

You have a dict whose keys are JSON strings representing dicts (and whose values you haven't shown us). 'name' isn't a key in that dict; "{u'name': u'Pooled Set 1', u'tags': [u\\'thing1\\', u\\'thing2\\'], u'sets': …}" is.

Without knowing what the original data are, or even what the rest of the parsed myDict looks like (you've only shown us part of the first key in the dict), it's hard to be sure what exactly you should be writing instead of what you've actually written.

You could of course do something like this:

for key, value in myDict.items():
    actual_dict = json.loads(key) # does the value mean anything?
    print actual_dict['name']

… but parsing data incorrectly and then trying to fix them up after the fact is almost always a bad idea.

Have you considered using fixtures? Given that you already have a json file in the proper format of the django model, you can just run

python manage.py loaddata fixture_name.json

and it will directly update your model

Reference: https://docs.djangoproject.com/en/dev/howto/initial-data/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM