python - json.loads 在 django 中不起作用

标签 python json django

我的 mysql 数据库中有一个对象(或字符串?我不确定..),我想将其返回到 View 中的 python 字典,然后处理它,然后发送回 html。

这是我在views.py中的代码:

def measure_detail(request, measurement_id):

        _ClickedPts = ClickedPts.objects.get(measurement=measurement_id)

        _ClickedPts = json.loads(_ClickedPts)

        return render(request, 'measurement_detail.html', {'measurement': _measurement, 'clicked_pts': _ClickedPts})

_clickedPts 看起来像这样:

{0: {u'loc': [1, 2], u'pts': [[456.45631334215614, 1155.23758883418], [1087.2590986710893, 1175.6156203824098]], u'imsize': (3264, 2448)}, 9: {u'loc': [1, 2], u'pts': [[838.4383679397915, 1183.738210969312], [1751.0879501479042, 1179.0747927841176]], u'imsize': (3264, 2448)}, 28: {u'loc': [1, 2], u'pts': [[1544.854017880959, 1041.081669022464], [2262.6099907645976, 1044.953878976804]], u'imsize': (3264, 2448)}, 14: {u'loc': [1, 2], u'pts': [[1122.5721676687076, 1211.5634319190933], [2053.740361759838, 1221.0344281491446]], u'imsize': (3264, 2448)}, 15: {u'loc': [1, 2], u'pts': [[1037.1904375418785, 1166.702956796377], [1959.451782586886, 1190.2974020603272]], u'imsize': (3264, 2448)}}

最佳答案

您的字符串不是正确的 JSON 字符串,实际上看起来像 Python JSON 对象。您最好使用 ast.literal_eval 将此字符串转换为 Python JSON 对象。只需调用 ast.literal_val(_ClickedPts) 而不是 json.loads(_ClickedPts) 即可获得您想要的内容。

https://docs.python.org/2/library/ast.html#ast.literal_eval

关于python - json.loads 在 django 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38250384/

相关文章:

java - JSON 数据的 Ajax 响应

json - 哪个 bean 在 Spring Boot 中将对象转换为 Json?

Ajax Response Content-Disposition 附件

django 电子邮件消息异常

python - 如何以编程方式获取 Django 模型字段的 max_length?

python - Django 谷歌应用程序引擎错误

python - Matplotlib 箱线图 x 轴

如果我去 bash 然后 tcsh (anaconda),则 Python3 只在 tcsh 中打开

python - 如何在 Python 中将 Azure Blob 存储中的 CSV 作为流处理

python - 在 SelectField 和 HiddenField 之间动态更改 WTForms 字段类型