【问题标题】:Parsing a django object in template with javascript使用 javascript 解析模板中的 django 对象
【发布时间】:2018-09-30 10:21:09
【问题描述】:

我正在尝试在 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
    }
]

如何解析“字段”属性中的数据?我希望能够让 parsedData.copper 返回“21”或类似的东西。谢谢!

【问题讨论】:

标签: javascript json django serialization


【解决方案1】:

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

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

【讨论】:

  • 是的,这给了我想要的结果。然后,要访问“字段”对象中的特定值,我必须使用例如:console.log(parsedData[0].fields.copper),它根据需要返回“21”。
猜你喜欢
  • 2016-11-13
  • 2011-03-21
  • 2017-07-29
  • 2023-03-11
  • 1970-01-01
  • 2022-01-26
  • 2014-02-11
  • 2011-07-24
相关资源
最近更新 更多