django->html传递js json

context = {
    "testjson1": json.dumps(  ["Mon", "Tue", "Wed", "Thu", "Fri"]    ),
    "testjson2": json.dumps(  '["Mon", "Tue", "Wed", "Thu", "Fri"]'   ),
} return render(request, 'pyecharts/chart2.html', context)

 


json.dumps对象, 

前端:
<script>
    // 从 Django 传来的对象JSON 字符串, var赋值后是obj
// 若是 string json字符串, var赋值后是string

var testjson1 = {{ testjson1 | safe }}; var testjson2 = {{ testjson2 | safe }}; console.log(typeof testjson1); // 应该是 "obj" console.log(typeof testjson2); //应该是string <script>

 

上面,testjson2因为是字符串,不是obj,若要当obj使用里面的数据,必须parse成obj
test2=JSON.parse(testjson2)


console.log(typeof testjson1); 

image

 

image

 注意,类型不能错误

安全做法,先判断类型

function safeParse(jsonOrObj) {
  if (typeof jsonOrObj === 'string') {
    return JSON.parse(jsonOrObj);
  }
  return jsonOrObj; // 已经是对象,直接返回
}

// 使用示例
const result1 = safeParse('{"x":1}'); // 解析
const result2 = safeParse({ x: 1 });  // 直接返回

 



posted @ 2025-12-02 15:36  花生与酒  阅读(4)  评论(0)    收藏  举报