[英]Error parsing json content through JSON.parse()
我正在使用 django 中的 json_script 模板標簽從上下文視圖中獲取 json。
我收到這樣的 json
{{rules|json_script:"rules"}}
<script lang="javascript">
const rules = JSON.parse($('#rules').text())
</script>
這是我從{{rules|json_script:"rules"}}
收到的
<script id="rules" type="application/json">{"id": 10, "string": "demo", "profile": "Alumno Demo", "license": "Licencia no facturable por usuario demo", "field": "codigo_usuario", "include": true, "order": 1, "uppercase_sensitive": false, "dateadded": "2020-05-11T08:06:35Z", "billable": false}</script>
但是當我嘗試 JSON.parse 我收到此錯誤:
VM760:5 Uncaught SyntaxError: Unexpected token R in JSON at position 5
我究竟做錯了什么? 如果我復制腳本的內容,它似乎是正確的 json。
提前致謝!
實際上 $('#rules').text() 正在返回 jQuery n.fn.init function。
查看 jQuery 庫的代碼:
`var jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context );
};`
它返回一個空的 function 以防它無法在 DOM 上找到元素。
你可以做什么:
1 . 像這樣使用基本的 javascript 方法 getElementsByTagName :
document.getElementsByTagName('script')
這將返回一個腳本元素數組,在您的情況下,您將獲得 2 個元素,並且只需使用 text 屬性來獲取腳本標簽內容。
JSON.parse(document.getElementsByTagName('script')[0].text)
2 . 您還可以在腳本中聲明一個變量並像這樣解析 JSON:
var stringifiedJson = {"id": 10, "string": "demo", "profile": "Alumno Demo", "license": "Licencia no facturable por usuario demo", "field": "codigo_usuario", "include": true, "order": 1, "uppercase_sensitive": false, "dateadded": "2020-05-11T08:06:35Z", "billable": false}; JSON.parse(stringifiedJson);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.