JavaScript is struggling to interpret the JSON string

I am transmitting a JSON string from my Django view to a JavaScript file named idbop.js on the client side. In Django, I am utilizing the serializer to convert query results into JSON format. Here is an excerpt from my views.py file in Django:

def index(request):
template='posts/index.html'
results=feed.objects.all()
jsondata = serializers.serialize('json',results)
context={
    'results':results,
    'jsondata':jsondata,
}
return render(request,template,context)

On the client side, I am accessing the variable jsondata in JavaScript like this:

var jsondata="{{jsondata}}".replace(/"/g,"\"");

The content of the jsondata variable is in string form. When I attempt to parse it using var data = JSON.parse(jsondata);, an error is thrown stating:

SyntaxError: JSON.parse: bad control character in string literal at line 1 column 344 of the JSON data.
It seems that the issue lies with the whitespace at position 344 within the jsondata, which is actually a part of the string value. This is what my JSON string looks like:

[
    {
        "model": "posts.feed",
        "pk": 1,
        "fields": {
            "author": "J Watson",
            "title": "Service Worker",
            "body": "A service worker is a type of web worker. It's essentially a JavaScript file that runs separately from the main browser thread, intercepting network requests, caching or retrieving resources from the cache, and delivering push messages.

Because workers run separately from the main thread, service workers are independent of the application they are associated with. This has several consequences:"
        }
    }]

Answer №1

To ensure the security of your javascript content within your template, you have the option to either utilize the safe or escapejs builtins. When using the safe method:

var jsonData = {{ jsonData|safe }}

Alternatively, you can use escapejs like so:

var jsonData = JSON.parse({{ jsonData|escapejs }})

Answer №2

Utilizing the safe built-in template filter on your {{jsondata}} would be beneficial. For your specific case, the implementation should resemble this:

var jsondata={{ jsondata | safe }}

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

Adding rows to a Datatable using an object array in rows.add()

Attempting to refresh my current Datatable by fetching new data using an Ajax function. Despite trying various solutions from other sources, the table does not update as expected. The function being used is shown below: $.ajax({ url: "<?php echo s ...

Executing OPENJSON in a SQL Server 2016 stored procedure

After following the example provided in this forum post: Click here, I encountered an issue with my syntax. The code successfully retrieves the data from a source but fails to populate the table due to errors in my implementation of the OPENJSON function. ...

Using JSON.stringify to format data and making an asynchronous $http request

I am working with a JavaScript string that looks like this: user_fav = "21,16"; I need to process this string through a function so that it becomes a JSON array with an id key, like this: {"id":21},{"id":16} This JSON array is then used in an $http req ...

The condition for the result of a jQuery $.post call

I've customized this code obtained from the jQuery website by incorporating a condition into it. However, regardless of the outcome, it consistently enters the first 'if' statement. How can I ensure that my condition is functioning correctly ...

jsTree unable to locate node using the provided ID

Implementing the jsTree on the webpage is not a problem for me. I have experimented with numerous suggestions from different sources. $('#myTree').jstree({ .... }) .on('loaded.jstree', function (e, dta) { var t = $('#myTree&a ...

The Angular $filter functionality does not seem to be functioning properly in Firefox and Safari browsers

I am trying to format the date using Angular.js, but it seems to only be functioning properly in Chrome. Below, I have included my code for reference. $scope.timestamp=2016-12-16 07:58:30 AM $scope.orginalTime= $filter('date')(new Date($scope.t ...

When a change occurs in the <input/> element within a <div>, the onChange event in React will be triggered

Upon entering text into the input, the onChange function is triggered on this code snippet. How is it possible for the onChange event to occur on a div element? Is there documentation available that explains this behavior? class App extends Component { ...

What is the best way to split an AJAX response into different variables and effectively retrieve each one of them?

When using AJAX to fetch data from a database and display it in a text box, most examples found online only show how to display the AJAX response in one text box. But what if we need to separate multiple PHP variables retrieved from the AJAX response and d ...

Discovering information within an array in MongoDB

Here is a sample collection: { "name":"silver", mywants:[ {"_id":objid(545454ddfdf5),mark:{"english":100,"math":100,"science":100}}, {"_id":objid(5878784dfd5d),mark:{"english":100,"math":100,"science":100}}, {"_id":objid(5454dfd44545), ...

What is the reason that the variable is not accessible after the switch block?

While working on my code, I encountered a dilemma. I needed to print the value of the 'text' variable after a switch block. However, I mistakenly did not include an expression in the switch statement which caused it to skip the default case and t ...

Using Django's Foreignkey with editable fields and a select field - integrating it into a form

Forgive me if this question has been asked before. I have been grappling with this issue for weeks and have come up empty-handed in my search for a solution. Here is the gist of my problem: I am dealing with a Model that has numerous fields. Let's c ...

I am trying to move to a different page, but for some reason the router.navigate function is not functioning within the subscribe

//I am attempting to redirect to another page once the subscribe method is executed, however I am encountering issues with the router.navigate function within the subscribe method. //In an effort to address this issue, I have attempted to store the data r ...

Creating a class that can be easily mocked for connecting to mongoDB

I've been attempting to develop a class that connects to MongoDB (and accesses a gridFS connection using gridfs-stream). However, I have encountered two specific problems: Sometimes, I receive the mongo Error server instance in invalid state connect ...

Adding JavaScript to dynamically loaded AJAX content

I'm new to AJAX and JavaScript and unsure of how to get it working. Here is the website: When you click on portfolio images, the details load via AJAX. I want to create a slideshow for projects with multiple full-sized images. However, due to the co ...

Is it feasible to convert a Google Drive spreadsheet into JSON format without needing the consent screen?

I'm working on incorporating a JSON feed directly from a private spreadsheet (accessible only via link) onto my website. In order to do this, I must create a new auth token using OAuth 2.0, which is not an issue. However, the Google Sheets API v4 mand ...

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...

Is there a way to prevent Chrome from highlighting text that matches the content of a `position: fixed` element?

I currently have a Toc element in my HTML with the property position: fixed. (This means it remains in place as you scroll) My goal is to prevent Chrome's Find Text feature from recognizing text within that Toc element. (Ideally using JavaScript) ...

How to Build a Bootstrap Table using PHP and JSON Data?

Trying to use json data like this https://i.sstatic.net/iRUUE.png {"endpoint":"127.0.0.1","id":1,"identifiers":["license:LICENSEKEY","xbl:XBLKEY","live:LIVEKEY","discord:DISCORDID&q ...

Utilize JSON data to dynamically populate TextFields or Select menus depending on a specific key in the JSON object

As I retrieve multiple JSON groups from an API, each group contains one or more questions objects. The task at hand is to attach each question along with its corresponding response to a textField. Based on the value of QuestionType, it will be decided whet ...

Error: Attempting to access 'push' property on an undefined object

Encountered an Error After implementing the useNavigate function, I successfully resolved the issue. let params = useParams(); let navigate = useNavigate(); const dispatch = useDispatch(); const productId = params.id; const [qty, setQty] = useStat ...