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);


注意,类型不能错误
安全做法,先判断类型
function safeParse(jsonOrObj) { if (typeof jsonOrObj === 'string') { return JSON.parse(jsonOrObj); } return jsonOrObj; // 已经是对象,直接返回 } // 使用示例 const result1 = safeParse('{"x":1}'); // 解析 const result2 = safeParse({ x: 1 }); // 直接返回

浙公网安备 33010602011771号