使用javascript在模板中解析django对象

时间:2018-04-19 19:47:31

标签: javascript json django serialization

我试图在javascript中读取Django对象。我像这样序列化了django模型对象:

recent_data = leafSamples.objects.filter(field_name=str(fields_distinct[0])).latest('id')
recent_data_json = serializers.serialize('json', [recent_data])

接下来,我尝试在javascript中解析JSON数据:

var recentData = {{recent_data_json |safe}};
parsedData = JSON.parse(recentData);
console.log(parsedData)

但是,我一直收到错误:

SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data

字符串化时,我的数据如下所示:

[
    {
        "fields": {
            "copper": "21",
            "guess": null,
            "zinc": "32",
            "chloride": "",
            "potassium": "2.36",
            "irrigation": null,
            "manganese": "19",
            "calcium": "1.81",
            "iron": "66",
            "magnesium": "0.37",
            "nitrogen": "3.14",
            "boron": "46",
            "date": "2018-04-08",
            "sulfur": "0.33",
            "field_name": "104A",
            "age": null,
            "phosphorus": "0.40"
        },
        "model": "scoutapp.leafsamples",
        "pk": 1126
    }
]

如何解析“fields”属性中的数据?我希望能够让parsedData.copper返回“21”,或者其他东西。谢谢!

1 个答案:

答案 0 :(得分:0)

JSON.parse解析字符串,但是你用一个列表来提供它。您可以尝试添加单引号和escapejs过滤器:

var recentData = '{{recent_data_json | safe | escapejs }}';