我有一个Django模型
class StateCensusHistory(models.Model):
id = models.AutoField(primary_key = True)
year = models.IntegerField()
population = models.TextField()
density = models.TextField()
pop_change = models.TextField()
def __unicode__(self):
return "%d, %s\n" % (self.year, self.population)
class Meta:
app_label = "app"
db_table = "state_census_history"
保存列表的结果,通过json.dumps(list_object)
将几个列表转储到json字符串。通过Serializers json转换查询时返回此字段。我的问题是,由于SyntaxError
,JSON.parse()正在抛出unexpected token u
。
如果不修改文本字段本身,我该如何解决这个问题?
在我的视图文件中,我获取了查询集并通过
返回序列化数据return HttpResponse(json.dumps({"success" : "true",
"data" : serializers.serialize("json", countyData)}),
mimetype = "application/json")
并通过
解析var pop = JSON.parse(data[0].fields.density);
正在解析的示例返回字符串值是
{\"density\": \"{u'Penobscot': 40.75222856500098, u'Sagadahoc':
122.27083333333333, u'Lincoln': 67.97977755308392, u'Kennebec':
123.12237174095878, u'Waldo': 48.02117802779616, u'Cumberland':
288.9285325791363, u'Piscataquis': 3.9373586457405247, u'Hancock':
30.698239582715903, u'Washington': 12.368718341168325, u'Aroostook':
10.827378163074039, u'York': 183.47612497543722, u'Franklin':
16.89330963710371, u'Oxford': 25.171240748402518, u'Somerset':
12.425648288323485, u'Knox': 108.48302300109529, u'Androscoggin':
208.75502815768303}\"}
答案 0 :(得分:3)
您要对数据进行两次编码。它已经是来自序列化调用的json,也不需要调用json.dumps。