AngelQuesada
AngelQuesada

Reputation: 431

Error parsing json content through JSON.parse()

I'm using the json_script template tag from django to take a json from a context view.

I receive the json like this

{{rules|json_script:"rules"}}

<script lang="javascript">
    const rules = JSON.parse($('#rules').text())
</script>

this is what i receive from {{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>

But when i try to JSON.parse I receive this error:

VM760:5 Uncaught SyntaxError: Unexpected token R in JSON at position 5

What am I doing wrong? If I copy the content of the script it seems like a correct json.

Thanks in advance!

Upvotes: 0

Views: 164

Answers (1)

Aman Kumayu
Aman Kumayu

Reputation: 389

Actually $('#rules').text() is returning a jQuery n.fn.init function.

Looking at the code of jQuery library:

`var jQuery = function( selector, context ) {
   return new jQuery.fn.init( selector, context );
};`

it returns an empty function in case it is unable to find an element on DOM.

What you can do:

1. Use Basic javascript method getElementsByTagName like this:

document.getElementsByTagName('script')

this will return an array of script elements, in your case you will get 2 elements and just use text attribute to get script tag contents.

JSON.parse(document.getElementsByTagName('script')[0].text)

2. You can also declare a variable in your script and parse JSON like this:

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

Upvotes: 2

Related Questions