when passing a JavaScript symbol in Django's JSON objects, it does not display properly

When working with Django (2.2), my goal is to send a JSON response in this format:

return JsonResponse(data, safe=False)

Within the data object, there is a value that looks like this:

"unit": "\u33A5"

(cubic meters).

However, when I attempt to display this value on my HTML page using JavaScript, I end up seeing the literal representation instead of the cubic meters symbol.

Unfortunately, I cannot provide the exact JavaScript code since this symbol is meant to act as a y-axis label for an ECharts graph. But I have tried something along these lines:

yAxis: {
    type: 'value',
    name: data.unit,
    nameLocation: 'middle',
},

If I replace data.unit with the hardcoded "\u33A5" within the options, the cubic meters symbol displays correctly.

So, my question is: How can I properly serialize or display JavaScript symbol codes when utilizing Django's JSON responses?

Answer №1

To start, create a subclass of DjangoJSONEncoder with the ensure_ascii set to False:

from django.core.serializers.json import DjangoJSONEncoder

class UnicodeDjangoJSONEncoder(DjangoJSONEncoder):
    def __init__(self, **kwargs):
        kwargs['ensure_ascii'] = False
        super().__init__(**kwargs)

Next, when using JSONResponse, make sure to provide the custom encoder and set safe parameter to False:

return JsonResponse(data, encoder=UnicodeDjangoJSONEncoder, safe=False)

Just a side note: The safe parameter doesn't affect how special symbols or unicode characters are handled, it only allows for non-dictionary top level items.

Javascript Component

If you're working with JSON data in JavaScript and passing it to eCharts, the JSON.parse() method should handle the encoding properly:

const jsonData = '{"type": "value", "unit": "\u33A5/d", "nameLocation": "middle"}'
const data = JSON.parse(jsonData)
document.querySelector('#y-axis').appendChild(document.createTextNode(data.unit))
<div id="y-axis"></div>

If there are still issues, consider storing the actual unicode character in the database, utilize the custom encoder mentioned earlier to prevent re-escaping, and then pass the data to eCharts.

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

Why is the validate function not being executed in the Backbone Model?

I am a beginner in learning Backbone and I am attempting to implement simple validation in my Person Model. However, I am facing an issue where the validate method does not run when I set a new age. Can someone guide me on where I might be making a mistake ...

Optimal code structuring for a javascript plugin

Hey there, I came across some intriguing posts on this topic, but I believe it's a very personal question that requires a tailored answer. So, I'm reaching out to ask you: what is the most effective way to organize my code for a JavaScript plugin ...

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

Looking to extract the first URL from a string using JavaScript (Node.js)?

Can someone help me figure out how to extract the first URL from a string in Node.js? " <p> You left when I believed you would stay. You left my side when i needed you the most</p>**<img src="https://cloud-image.domain-name.com/st ...

Prevent the submission of the form if the textfield does not contain any

Is there a way to prevent form submission when a textfield is empty? Currently, my script allows for new empty records to be inserted into the database even when the textfield is empty. $(document).ready(function(){ $("#form1").on('submit', ...

ESLint and Prettier are butting heads when trying to run their commands consecutively

My package.json file includes two commands: "format": "prettier --write \"{src,{tests,mocks}}/**/*.{js,ts,vue}\"", "lint": "eslint . -c .eslintrc.js --rulesdir eslint-internal-rules/ --ext .ts,.js,.vue ...

Enhancing Security in the apex.server.process Function in Oracle APEX

Once we have disabled a button using client-side JavaScript, our goal is to initiate an Ajax call to create a record in a database table through an On-Demand Process. However, there is a concern that users could bypass this process by making similar calls ...

React Grid by DevExtreme

Does anyone have a solution for adjusting the fontSize of the TableHeaderRow in a DevExtreme React Grid? Here is some code from a specific website () that I've been exploring: import * as React from 'react'; // Other imports... const Ad ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

Extracting data from a web service and populating an OWC11 spreadsheet with 10,000 rows

Having an issue with the web service call taking too long to return. The ASP.NET page is taking over a minute to start loading. Currently, I am using C# Response.Write() to output the data to Javascript for insertion into OWC11 spreadsheet. I'm lookin ...

Will other functions in the file run if only a single function is imported?

The file bmiCalculator.ts contains the following code: import { isNotNumber } from './utils'; export default function calculateBmi(height: number, weight: number) { const bmi = weight / Math.pow(height / 100, 2); if (bmi < 18.5) { re ...

Problems with the firing of the 'deviceready' event listener in the PhoneGap application

Utilizing vs2012, I have been working on a PhoneGap application. Within this application, the following JavaScript code is being used: document.addEventListener("deviceready", onDeviceReady, false); function onDeviceReady() { // alert("hh") ...

Ways to halt a message callback?

Looking at some lines of code from a canvas sprite animation on GitHub, I am curious about how to stop the animations once the sprite has finished. window.requestAnimFrame = (function(callback) { // Function for handling animation frames return window.r ...

Ensuring continuous execution of JS EventListener

The other day, I received a solution from someone on this platform for a script that changes the color of a div when scrolling. Here is the code I implemented: const x = document.getElementById("menuID"); window.addEventListener("scroll", () => { ...

Using slashes in the import statement versus using require statement

Note: I am currently running on node version 14.1 Here is the line of code I'm experimenting with: import "module-alias/register"; This results in the following error: Error [ERR_MODULE_NOT_FOUND]: Cannot find module The error seems to point to t ...

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

I am looking to dynamically generate HTML elements using AngularJS based on data from a JSON file

Although there are existing answers to this question, I have a specific approach that I need help with. I've already made progress but could use some guidance. This is my Controller : angular.module('dynamicForm.home-ctrl',[]) .con ...

Customizing the appearance of an HTML element using user-input text styling

On my webpage, there are two text areas and a division. One of the text areas is meant for users to input HTML code, while the other is for CSS code. Whenever a button is clicked, a JavaScript function will be triggered to display the combined HTML and CSS ...

Problems encountered when trying to deploy on Firebase

I've been working on deploying my web app to Firebase, and I successfully ran the deploy script. However, when I try to access the URL, instead of seeing my app, I'm greeted with the Open Hosting Documentation page. Here is what my firebase.json ...

Unable to successfully submit a request for login information using an AJAX call

I need to capture the user ID and password entered by the user and send it to the Server. Here is the Javascript code I am using: <script> function Display(){ var ID = document.getElementById("user_id").value; document.getEl ...