0

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!

1
  • Can you console.log($('#rules').text()) and post the output? Commented May 12, 2020 at 12:48

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

You're right, but I dont get one thing: Why if I use getElementByIid I get: <div class="collapse" id="rules"> ... </div> and when I get use getElementsByTagName('script')[20].text I get <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>
Just because scripts elements doesn't work with an id attribute, it can only have async, charset, src, type, defer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.