简体   繁体   English

如何序列化 python class 以传递到 javascript

[英]How to serialize a python class to pass onto javascript

I am trying to pass a variable onto a javascript in flask.我正在尝试将变量传递到 flask 中的 javascript 上。 But I get the following error: TypeError: Object of type MyClass is not JSON serializable但我收到以下错误: TypeError: Object of type MyClass is not JSON serializable

Code:代码:

routes.py:路线.py:

@app.route('/')
@app.route('/index')
def index():
    data = {
        "foo": myObj
    }
    return render_template('index.html', data=data)

To note that myObj is a custom class object of type MyClass.要注意myObj是 MyClass 类型的自定义 class object。

index.html:索引.html:

    <script src="{{ url_for('static', filename='my_script.js', type="module") }}" crossorigin="anonymous"
            defer>
    </script>
    <script>
        let data = {{ data|tojson }};
    </script>

my_script.js: my_script.js:

console.log(data);

I tried to simply write {{ data }} instead of {{ data|tojson }} but I get the errors: Uncaught SyntaxError: Unexpected token '&' and my_script.js?type=module:1 Uncaught ReferenceError: data is not defined at my_script.js?type=module:1我试图简单地写{{ data }}而不是{{ data|tojson }}但我收到错误: Uncaught SyntaxError: Unexpected token '&' and my_script.js?type=module:1 Uncaught ReferenceError: data is not defined at my_script.js?type=module:1

I know that there are a lot of question, but I do not find one that addresses this issue.我知道有很多问题,但我找不到解决这个问题的问题。

The problem here is that you're trying to pass a Python object to Javascript.这里的问题是您试图将 Python object 传递给 Javascript。 It's not going to work.这是行不通的。 The best thing to do is convert it to JSON, which is compatible between Python and Javascript.最好将其转换为 JSON,在 Python 和 Javascript 之间兼容。

Using the json module you can serialise your dictionary.使用json模块,您可以序列化您的字典。 However, the Python object of MyClass is not JSON serialisable.但是, MyClass的 Python object 不是 JSON 可序列化的。 You should be able to serialise the __data__ attribute instead, which is a dictionary of attributes in the object.您应该能够序列化__data__属性,它是 object 中的属性字典。

Change your Python like this:像这样更改您的 Python :

import json

@app.route('/')
@app.route('/index')
def index():
    data = {
        "foo": myObj.__dict__
    }
    return render_template('index.html', data=json.dumps(data))
 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM