1

I've searched around and all I know is that somehow the JSON is getting corrupted. I am calling json.dumps on a list of dictionaries and then saving it into a django model object. When I try to read it back in by calling json.loads I am getting the Expecting property name: line 1 column 2 (char 2) exception thrown.

Here is my code. If there is a conversation already then it tries to load the text into the messages list and append the new one (but it doesn't succeed). If it doesn't exist then it just appends it to an empty list and saves it (which works).

convo = Conversation()
messages = []
if request.POST.get('convo_pk',''):
    convo = Conversation.objects.get(pk = request.POST['convo_pk'])
    messages = json.loads(convo.text) #this is where it dies
else:
    convo.offer = Offer.objects.get(pk = request.POST['offer_pk'])
new_message = json.loads(request.POST['message'])
messages.append(new_message)
convo.text = messages
convo.save()

From the django admin panel this is the json that is being saved.

[{u'body': u'this is the message body', u'user_id': u'8', u'name': u'Mark', u'time': u'2013-10-10-16:32'}]
4

3 回答 3

3

那不是 JSON。当你去弄清楚为什么它不输出 JSON 时,你可以使用ast.literal_eval().

>>> ast.literal_eval('''[{u'body': u'this is the message body', u'user_id': u'8', u'name': u'Mark', u'time': u'2013-10-10-16:32'}]''')
[{u'body': u'this is the message body', u'user_id': u'8', u'name': u'Mark', u'time': u'2013-10-10-16:32'}]
于 2013-10-11T06:22:22.223 回答
0

http://jsonlint.com/

给出了这个错误

Parse error on line 2:
[    {        u'body': u'thisisthe
--------------^
Expecting 'STRING', '}'

你需要摆脱'你'

于 2013-10-11T05:43:23.580 回答
0

所以它不起作用的原因是因为我在保存之前忘记将文本编码回 json (保存的只是对象的 python 表示)。但无论如何,我最终还是使用了jsonfield。它会自动将您的对象转换为 json 并保存它们。

于 2013-10-12T16:35:42.867 回答