What is the correct way to set the encoding for a server-side string?

As someone who is fairly new to web development, especially on the front end side, I am facing an issue with encoding. I am using python 2.7 and Flask for this project.

  • Environment: Python 2.7, Flask

The problem arises when I send json data to a server in this manner.

@app.route("/test")
def test():
    data = json.dumps({"name": "홍길동", "id": "gildong1"}, ensure_ascii=False)
    return render_template("testpage.html", data=data)

When I print out the data on the server side, the Korean characters display correctly.

However, when I receive the data in JavaScript like this:

var t_data = JSON.parse({{data}});

The output in the console shows escape characters like this:

var t_data = JSON.parse("{"name": "홍길동", "id": "gildong1"}");

Update

I suspect that the issue might be related to the Content-Type header. When examining it in the debugger, I noticed that the Content-Type was set to u'text/html'. I attempted to modify my code as follows, but it still displays Unicode characters:

@app.route("/test")
def test():
    data = json.dumps({"name":"홍길동", "id": "gildong1"}, ensure_ascii=False).encode("utf8")
    resp = make_response(render_template("TestPage.html", data=data))
    resp.headers['Content-Type'] = 'text/html'
    return resp

Answer №1

One solution is to encode the response on the server side by converting your line using JSON.dumps.

`data = json.dumps({"name": "홍길동", "id": "gildong1"}, ensure_ascii=False).encode('utf8')`

Alternatively, you can handle this on the client side with regex. Use it to replace all occurrences of " with "

var input = '{"name": "홍길동", "id": "gildong1"}'
input = input.replace(/(")/g,'"');
console.log(input); // {"name": "홍길동", "id": "gildong1"}

Answer №2

Have you given the jsonify() function a try instead of using json.dumps()? For more information, refer to this link and take a look at this small code snippet:

from flask import Flask, jsonify, json
app = Flask(__name__)
data = json.dumps({"name":"홍길동", "id": "gildong1"})
with app.app_context():
  data2 = jsonify(name="홍길동", id= "gildong1")
print (data)
print(data2.get_json())
# output
# {"id": "gildong1", "name": "\ud64d\uae38\ub3d9"}
# {'id': 'gildong1', 'name': '홍길동'}

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

I need help fixing the alignment of the lengthmenu and export buttons in Bootstrap Datatables Javascript. They are too close together and I want to create a line break between

I'm currently working on a searchable table that requires users to export their results and choose the number of entries they want to see. However, everything appears too congested. I am looking to create some spacing by adding line breaks, paragraphs ...

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

Upon submission, the form is processed and 'false' is returned

Does anyone know how I can use ajax to save form data? I am encountering an issue where the page refreshes when all entries are correct. If I input any incorrect data and submit, it displays an error. However, if I then fill in all correct information, it ...

Utilizing C# ASP.NET to Extract Data from a Web Page Post JavaScript Execution

Looking to extract all links from a web page in order to review where cookies are being set for compliance with UK legislation. In an effort to streamline the process, I am exploring automation options to save time. However, a challenge I am facing is tha ...

Is it possible to utilize the function(e) multiple times within a single file?

Can the same function be used multiple times in a single file? document.getElementById('one').onlick = function test(e) { var key = e.which; if(key === 13) { document.getElementById('two').c ...

I currently have a set of 6 popovers that all open simultaneously, but I am looking to make them open sequentially, one after

My component generates a div with 6 different experiences, each with its own popover. However, when I click on an experience to open its popover, all 6 popovers appear. How can I assign a unique ID to each popover? This is the code for my experience compo ...

Response is null in the success callback of the AJAX function

Within my codebase, I have a function designed to remove a user from the database by utilizing a Web API call. This server-side function provides feedback in the form of a string confirming whether the user was successfully located and deleted or if the pr ...

execute a rigorous compilation during the ng build angular process

I am currently working on a project using angular-cli and I have configured my package.json with the following scripts: "scripts": { "ng": "ng", "build": "ng build --base-href /test/", "prod": "ng build --prod --base-href /test/" } According to the ...

Strategies for resolving the error message "undefined" following the mapping process

Currently, I am utilizing a custom API to retrieve data. In order to accomplish this, I have structured an object that holds all the necessary data to be retrieved in a dynamic manner. My approach involves using the fetch() function to perform these data r ...

Collapsing tabs feature in Bootstrap 4

I am working on a project with Bootstrap 4 Tab. My goal is to initially hide all tab contents and then show them when the corresponding tab is clicked. I achieved this by removing the active class from the tab-pane div. However, I encountered an issue wher ...

What is the best way to manage several asynchronous requests concurrently?

Can anyone recommend some valuable resources or books that explain how to effectively manage multiple asynchronous requests? Consider the code snippet below: Payment.createToken = function(data) { var data = data; apiCall("POST", "api/createToke ...

Loading various choices through ajax and subsequently assigning a specific value

After the page loads, I have a select field called #parentCatSelect that generates values using AJAX / PHP through the function acLoadParentCategories. This function serves two purposes: creating a new part (which works as intended) and updating an existi ...

How can I configure AngularJS intellisense in Visual Studio Code?

I've been customizing Visual Studio Code for better compatibility with our Angular 1.5 codebase at my workplace. Here's the progress I've made so far: Downloaded and installed TSD Ran the command tsd query -r -o -a install angular -s Added ...

Unable to Render Data URI onto HTML5 Canvas

I have been attempting for quite some time and feeling frustrated. I am facing issues with my Data URI image not being able to write to my canvas for reasons unknown .... Here's the code snippet ... function addImage() { var allfiles = $("#postAtta ...

methods for extracting header information using JavaScript

Is there a way to retrieve values from the header URL using JavaScript? Consider this scenario: www.example.com/content.html?param=value How can one extract this information upon redirecting to the page content.html? What techniques could be employed f ...

Unseen faces rendered by Three.js

When I load my OBJ file with a JPG texture onto a page, the faces are visible from one side but invisible from the other. The faces are visible on one side (albeit a little dark - apologies for that!) However, on the other side, the faces are not visible ...

I noticed that my Angular routes are prefixed with a '#%2F' before the specified URL in my app.js file

My Angular routes are set up in the app.js file like this: .config(function ($routeProvider) { $routeProvider .when('/', { templateUrl: 'views/main.html', controller: 'MainCtrl', controllerAs ...

validation schema designed specifically for values falling within the range of 0 to 1

Is there a way to adjust the schema so that users can only input values between 0 and 0.9? validationSchema: Yup.object({ ratio: Yup.number() .max(15, 'Must be 15 characters or less') .required('Required'), ...

Mapping data using MapState is a useful technique that can help organize and access data

Is it possible to use ...mapstate to fetch data from the store instead of directly accessing it like this.$store.state.workermanage.staff.staff? Any suggestions are appreciated, thank you. persons: this.$store.state.workermanage.staff.staff ...

Display stylized portion of text within JavaScript object

I am struggling with formatting a specific part of the text in my Ionic HTML list of cards. The content is populated by objects defined in my JS controller as shown below: <div class="list"> <div class="card" ng-repeat="item in eventsDay19"> ...