There was an issue with parsing the json data using the JSON.parse() function

Utilizing the json_script template tag in Django, I am obtaining a JSON from a context view.

The JSON is received as follows:

{{rules|json_script:"rules"}}

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

This is what I get 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>

However, when attempting to parse with JSON.parse, an error is encountered:

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

What could be the issue? Upon copying the script content, it appears to be a valid JSON format.

Your insights are greatly appreciated!

Answer №1

When you use $('#rules').text(), it actually returns a jQuery n.fn.init function.

If we take a closer look at the jQuery library code:

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

You'll see that it will return an empty function if it can't find an element in the DOM.

Here are some solutions:

1. You can use basic JavaScript method getElementsByTagName like this:

document.getElementsByTagName('script')

This will give you an array of script elements. In your case, there are 2 elements and you can access the text attribute to get the contents of the script tag.

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

2. Another option is to 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);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing quotation marks in ASP MVC4 when accessing Model values

I am currently working with a model in my view that includes a property named 'list of numbers' public myModel{ public string listOfNumber {get; set;} Within my controller, I assign a string value to this property public myController{ public ...

Unable to pass data from a Jquery ajax request to another function

I've written a basic ajax request using jQuery. Here is the code for my ajax function: var sendJqueryAjaxRequest = function(arrParams) { var request = $.ajax({ url: arrParams['url'], async: false, ...

The TypeConverter attribute in JsonConvert.SerializeObject() does not support conversion of the specified model in

I am currently working on a C# MVC application that handles data stored as JSON strings in an XML document and MySQL DB Tables. A recent requirement has come up to store JSON strings directly in MySQL Database fields, which need to be converted into C# obj ...

Django import failed, was functioning properly the previous week

Last week everything was working perfectly fine when I executed python manage.py runserver 8080. However, today I encountered a new error out of the blue, even though it was running smoothly just a week ago. A problem occurred: When I attempted to run &a ...

Serialization of dictionary containing intricate objects into JSON format

I need to convert the dictionary playersElo into a JSON format for saving and loading purposes. Unfortunately, since it is not naturally serializable, I am facing difficulties finding a suitable solution. playersElo={} # dictionary of {<int> : <P ...

Converting objects to arrays of objects in LuaScript-KrakenD: A guide

I have included the code snippet with a query that requires assistance in Lua or Krakend configuration, or both. (Note: Key does not exist) LuaScript local docDetails = responseData:get("DocDetails") ...

Continue executing without stopping

After making 4 ajax calls, the script is supposed to halt if record number 123456 is found. However, this specific record may appear in all four ajax responses. Despite this expectation, the code fails to stop processing. var endPoint0 = ''; var ...

Is the runTest.ts class in the vscode-test setup ever utilized in the project? Its purpose remains unclear even in the example project

Being a novice to Typescript, JavaScript, and VScode Extensions I have set up a vscode-test following the guidelines provided here: https://code.visualstudio.com/api/working-with-extensions/testing-extension#custom-setup-with-vscodetest Based on the hel ...

Dark opaque background image with Material-UI styling

I'm enclosing all the widgets within a CardMedia component, and adding an image. return ( <CardMedia image={bg} className={classes.bg}> <main className={classes.content}> <div className={classes.toolbar} /> <Grid contai ...

In JavaScript, I am looking to duplicate an image and place it back at its original location after it has been moved from its initial position

I am working with 3 draggable images and my objective is to ensure that each image returns to its original position when moved. Ultimately, I want the user to be able to interact with multiple instances of images 1, 2, and 3 on the page, all of which are d ...

Why is it that vue-cookies are functioning properly in one view, yet not in another?

In my Login.vue file, I successfully set a token cookie using the 'vue-cookies' package. The cookie is properly set and working. However, when I try to access the same cookie in another view, I encounter the following error in the Chrome console ...

Using JavaScript to parse Java objects into JSON data

I'm working on sending an array of POJOs as a response to an AJAX call. Within my POJO, the following toString() method is defined: @Override public String toString() { return "Expense [period=" + period + ", description=" + description + ...

Alert: Zone.js has identified that the ZoneAwarePromise '(window|global).Promise' has been replaced with polyfills. Kindly address this issue

Recently, I updated my Angular application from version 8 to 9. After updating the packages and successfully compiling the application, I encountered an error message in the Chrome browser console: Error: Zone.js has detected that ZoneAwarePromise `(wind ...

Setting color values for each pixel of a createGraphics object using P5.js

The code snippet provided below is intended to set the color value of each pixel within the createGraphics object to red. However, the output only displays a gray background. ////////////////////////////////////////////////////////// function setup() { ...

Utilizing Cookies in Django Middleware

Is it possible to utilize Custom Django Middleware (Django 1.9) to verify if an anonymous user has agreed to a website's terms & conditions? If the user has not clicked 'Agree', I want to display a dialog. I do not need to store this inform ...

What techniques can be used to avoid the MUI `DataGrid` from constantly re-rendering when a row is committed?

Check it out here to see how the MUI documentation implemented it: <b>const</b> rows = [/* Row Data */] <DataGrid rows={rows} {/* Other Props */} /> <sup>/*[1]*/</sup> The approach taken by MUI is quite impressive. It streaml ...

NoReverseMatch error occurred while trying to access the /NewListing page

When users try to create a new listing on my webpage using the form, everything seems to load fine initially. However, upon submission, an error occurs: NoReverseMatch at /NewListing Reverse for 'listing' with keyword arguments '{'list ...

Issues with retrieving the subsequent anchor element using Jquery Slider

(Apologies for the lengthy post. I like to provide detailed explanations.) Just starting out with Jquery, trying my hand at creating a custom image slider from scratch. Got the slider working with fade effects using this code: Javascript: $(document).re ...

Show the advancement of a process as it runs in a pop-up window

Currently, I am working on revamping a webpage to give it a more modern look. However, I'm encountering some challenges when trying to add simple functionality to a modal window. On the webpage, users upload a file, and upon clicking submit, a shell ...

Tips for managing numerous HTTP requests in Angular 6

I have a method that is trying to chain together 3 requests like this: showProfileDetails() { this.getUserInfo(this.currentUser.id).pipe( mergeMap(e => this.getAccounts(this.currentUser.id) ), mergeMap(e => this.getPayments ...