文章内容

2024/10/9 2:20:54,作 者: 黄兵

TypeError: Object of type CaseInsensitiveDict is not JSON serializable

需要将后端的 Json 数据在前端格式化输出,具体示例代码如下:

def index():
    init_swift = OpenStackSwiftUtil(current_user.generate_auth_token(), current_user.username)
    # 验证账户
    try:
        containers = init_swift.get_account_metadata()
    except Exception as e:
        return jsonify({'error': 'Failed to create bucket', 'details': str(e)}), 500
    return render_template('dashboard/index.html', containers=containers)

前端格式化 Json 数据代码:

<pre id="jsonDisplay"></pre>
<script>
// JSON 数据传递给前端(假设 containers 是后端传递过来的 JSON 数据)
const containers = {{ containers | tojson }};

// 格式化 JSON 并显示
document.getElementById("jsonDisplay").textContent = JSON.stringify(containers, null, 4); // 参数 4 表示每层缩进 4 个空格
</script>

但是出现了如下错误:

TypeError: Object of type CaseInsensitiveDict is not JSON serializable

出现错误的原因:

这个错误提示是因为 containers 的数据类型是 CaseInsensitiveDict,它不是原生的 JSON 序列化格式,Python 的默认序列化器无法直接将其转化为 JSON。

解决方案:

可以将 CaseInsensitiveDict 转换为普通的 Python dict,然后再传递给前端。在后端使用 dict() 函数来进行转换。

修改后代码如下:

def index():
    init_swift = OpenStackSwiftUtil(current_user.generate_auth_token(), current_user.username)
    # 验证账户
    try:
        containers = init_swift.get_account_metadata()
        # 将 CaseInsensitiveDict 转换为普通的 dict
        containers = dict(containers)
    except Exception as e:
        return jsonify({'error': 'Failed to create bucket', 'details': str(e)}), 500
    return render_template('dashboard/index.html', containers=containers)

这样就修复了这个错误。


其它相关推荐:

1、UTC TZ时间相关问题

2、python from...import *

3、Python retrying

4、python 获取本地时间

5、can't multiply sequence by non-int of type 'decimal.Decimal'

分享到:

发表评论

评论列表