Flask 发送的 JSON 格式的 Table 到达 JQuery 并转义反斜杠并且 JQuery 解析失败

Table in JSON format sent by Flask reaches JQuery with escaping backward slashes and JQuery fails to parse

Python代码:

from pandas import DataFrame
import socketio

Boxes = [{'Color':'Green','Color':'Green','Color':'Green'},{'Shape':'Square','Shape':'Square','Shape':'Rectangle'}]
df = DataFrame(Boxes,columns=['Color','Shape'])
df2 = df.to_json(orient='columns')
print(df2)
socketio.emit('tableMessage',{'theTable':df2},namespace='/test')
socketio.sleep(7) 

从 Python 打印的数据框:

{"Color":{"0":"Blue","1":"Red","2":"Red","3":"Red"},"Shape":{"0":"Square","1":"Square","2":"Square","3":"Rectangle"}}

Javascript - JQuery 代码:

socket.on('tableMessage', function(msg) {

        $('#table2').DataTable({

            data: msg.theTable,

            columns: [
            { title: "Color" },
            { title: "Shape" },
            ],
        });
    });

服务器控制台显示的数据帧:

Sending packet MESSAGE data 2/test,["tableMessage",{"theTable":"{\"Color\":{\"0\":\"Blue\",\"1\":\"Red\",\"2\":\"Red\",\"3\":\"Red\"},\"Shape\":{\"0\":\"Square\",\"1\":\"Square\",\"2\":\"Square\",\"3\":\"Rectangle\"}}"}]

有人知道如何在 Jquery 中将其正确显示为 table 吗? 提前致谢。

您需要先解析 JSON,然后再将其作为数据提供给 DataTables。像这样:

socket.on('tableMessage', function(msg) {

        $('#table2').DataTable({

            data: JSON.parse(msg.theTable),

            columns: [
            { title: "Color" },
            { title: "Shape" },
            ],
        });
    });
  1. 我用过 df = pd.DataFrame(data=[['Green','Tree'],['Yellow','Pyramid'],['Red','Circle'],['White','Ball']]) 在创建 Python 数据框时。
  2. df2 = df.to_json(方向='records') 将数据帧转换为 JSON 对象。
  3. '

socket.on('tableMessage', function(msg) {
        alert(msg.theTable);
        var someObject = JSON.parse(msg.theTable);
        $('#table2').DataTable({
            
            "searching": false,
            "ordering": false,
            "paging": false,
            "bordering":true,
            data: someObject,
            columns: [
            {"title": 'Color'},
            {"title": 'Shape'},
            ]

        });
    });

'

解析JQuery中的table。 4.

    <div class="container" id="content">
        <p>This is table</p>
        <table id="table2" class="display" width="25%" margin-left=10%>
            <thead>
                <tr>
                    <th>Color</th>
                    <th>Shape</th>
                </tr>
            </thead>
            <tbody></tbody>
        </table>
    </div>

显示在html。

谢谢