0

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.

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

i used a json field and it works. I didn't get how i should convert the string to a correct json to be able to store it in a textField.
As I said above, use json.dumps().
"Seem not to work" is not helpful. Exactly what happens? Exactly what are you trying? Do you get an error?
i tried it yesterday. the problem was this Expecting property name: line 1 column 2 (char 2). i don't remember exactly. i've to revert the project and try it out.

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.