EsseTi
EsseTi

Reputation: 4271

json parsing from models django

I've found some strange behaviour with python, and I don't get why.

This is how I create items and lists:

def createItemJson(self,id,url):
    ret={}
    ret['id']=id
    ret['url']=url
    return ret


def createListJson(self,i):
    ret_l = []
    for i in range(0,i,1):
        ret_l.append(self.createItemJson(i, i))
    return ret_l

And this is the output of a list of 3 elements:

[{'url': 0, 'id': 0}, {'url': 1, 'id': 1}, {'url': 2, 'id': 2}]

If I take this string and I do in shell A:

for v in data

I can print the 3 objects. N.B.len(data) is 3.

Now I store this data in the db as textfield (is it correct?). When I retrieve the object I get len with value 63.

Basically Django sees it as a string. What can I do? I tried to do json.load but it does not work.

Upvotes: 0

Views: 287

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599490

There is no JSON in the example you show. You have a Python dictionary. If you then "store it in a textfield" (note it would have been helpful to show exactly how you are doing that) you have presumably just dumped it as a string into that field. It's still not JSON, it's now a string representation of a Python dict, which isn't quite the same thing. json.load will "not work" (once again, exact error message would have been helpful) becaase it's not JSON.

You could try using json.dumps(my_dict) before storing it in the database, and json.loads() on the way out. Alternatively, use one of the many JSONField implementations you can probably find on a quick Google search.

Upvotes: 1

Related Questions