What is the best way to transmit a UTF-8 encoded JSON string over TCP using Python?

I've been struggling to send a UTF-8 encoded JSON string over TCP (Python 2.7). Below are some attempts and their results. The 'response' variable contains the JSON string I'm trying to send:

response = {"candidates":{"P":[{"mentionname":"Beyoncé","guess":[{"name":"BEYONCÉ","score":"1.00","eid":"72437"}]}],"E":[]}}

Attempt 1:

self.request.sendall(json.dumps(response+"\n", ensure_ascii=False))

This results in an error:

'ascii' codec can't encode character u'\xe9' in position 49: ordinal not in range(128)

Attempt 2:

self.request.sendall(json.dumps(response+"\n", encoding='utf8'))

This sends output to the other end (TCP client), but the last character of Beyoncé is incorrect:

{"candidates":{"P"[{"mentionname":"Beyoncé","guess":[{"name":"BEYONCÉ","score":"1.00","eid":"72437"}]}],"E":[]}}\n"

(The message is received on the client with message.decode('UTF-8')).

Attempt 3:

self.request.sendall(json.dumps(response+"\n", ensure_ascii=False, encoding='utf8'))

This results in an error:

'ascii' codec can't encode character u'\xe9' in position 49: ordinal not in range(128)

Attempt 4:

self.request.sendall(json.dumps(response+"\n").encode('utf8'))

This sends output to the other end (TCP client), but the last character of Beyoncé is incorrect:

{"candidates":{"P":[{"mentionname":"Beyoncé","guess":[{"name":"BEYONCÉ","score":"1.00","eid":"72437"}]}],"E":[]}}\n"

Attempt 5:

self.request.sendall(json.dumps(response+"\n", ensure_ascii=False).encode('utf8'))

This sends output to the other end, with the last character of Beyoncé as correct, but the double quotes are escaped:

{"candidates":{"P":[{"mentionname":"Beyoncé","guess":[{"name":"BEYONCÉ","score":"1.00","eid":"72437"}]}],"E":[]}}\n"

The last attempt is almost correct, except for the escaped double quotes. I understand this issue arises from "double encoding" but at the moment I have no choice but to use this workaround and remove backslashes in my TCP client code.

If anyone has a better solution, any help would be greatly appreciated! Regards, Patrick

Answer №1

It appears that you have placed the text in the response variable within the source code, and then set the file encoding so that the first two lines of the source file look like this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

For more information, refer to PEP 0263.

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

What is the best method to confirm if a text field contains the value I entered?

I'm a beginner in Python and Selenium, and I believe I need to use the Assert command to confirm that a text field contains the input from Selenium. After spending an hour searching for the solution, I still can't find it. This is the code I ha ...

JSONArray rewrites its contents

I am trying to generate an Array using the following method: json = new JSONObject(); jsArray = new JSONArray(); for (int i = 1; i < j; i++) { CheckBox checkBox = (CheckBox) findViewById(i); if (checkBox.isChecked()) { try { ...

What are the best practices for creating a RESTful HTTP API?

Assigned to outline a basic API, I embarked on some research and realized my understanding of the Internet may be flawed. I've spent countless hours searching online, sifting through articles, StackOverflow threads, and websites that seem to contradi ...

Enumerating groups of three vertices in a graph with multiple edges

Consider the following graph: import igraph as ig g=ig.Graph.Erdos_Renyi(10, 0.5, directed=True) To obtain its triad census, you can use the triad_census function: tc = g.triad_census() The output of 'tc' might look like this: 003 : -214748 ...

Trouble displaying data in Jquery JSON

I've been on the hunt for hours, trying to pinpoint where the issue lies within my code. Despite scouring different resources and sites, I can't seem to figure it out. Whenever I click "Get JSON Data," nothing seems to display below. Can someone ...

Rendering nested data structures in Django using a tree view

My backend server sends me a JSON response structured as follows: { "compiler": { "type": "GCC", "version": "5.4" }, "cpu": { "architecture": "x86_64", "count": 4 } } I am looking to represent this response ...

What is the best way to eliminate all elements from a duplicated Proto field in Python?

If I have the following .proto file: message Hello { } message World { repeated Hello greetings = 1; } What is the best way to clear all the items in the greetings field? ...

Problematic JSON Responses from WCF Service

In my WCF Class Library, I have a function called SampleJSON(string name) with the following Operation Contract: [OperationContract] [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, UriTemplate = "sample/{name}")] string SampleJSON(strin ...

Tips for capturing network traffic with Selenium WebDriver and BrowserMob Proxy in Python

For my project, I am working on capturing network traffic using Selenium Webdriver with Python. In order to achieve this, I need to utilize a proxy such as BrowserMobProxy. Everything works smoothly when using webdriver.Chrome: from browsermobproxy impor ...

Tips for showcasing an array in PHP with either JSON or XML structure?

I am currently working on creating an API web service using PHP. My goal is to display all the records from my database table in both JSON and XML formats using arrays. However, I am facing an issue where only one record is being displayed or receiving a r ...

What is the best way to parse JSON data in an Android application?

Can you assist with parsing the JSON in JAVA? The JSON format is provided below. { "contacts": [ { "id": "c200", "name": "Ravi Tamada", "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e39182995e8490938 ...

What are some methods for incorporating the test_proportion dataset into a machine learning algorithm?

I have a dataset containing 4000 CNN features for a binary classification problem. The only information I have about the test data is the proportions of labels 1 and 0. How can I instruct my model to predict test labels based on these proportions? Is there ...

What is the best way to handle binary files (such as images or audio) when serving them from a RESTful API that was built using

Exploring the most effective way to deliver files or bundles of files via a RESTful API. Considering options: Base64_encode files and include in JSON response Provide file links within JSON response Priority: Private access for certain files requiring ...

PHP Command Line Interface can effectively parse JSON strings provided as arguments

When utilizing PHP 5.3 and passing a JSON encoded string as an argument via command line... /usr/local/bin/php -q /path/to/script.php {"key":"test","cache":1} ... the code within script.php looks like this: <?php print_r($argv); ?> The output is: ...

CakePHP 1.3 - issue with JSON REST call not rendering correctly

I recently followed a tutorial on setting up a REST webservice for JSON and XML. While XML outputs correctly, I encountered an issue with JSON calls which resulted in the "view not found" message from Cake. To address this problem, I made some modificatio ...

The Python 2.6.6 version is throwing an ImportError when trying to import the Counter module from pandas library

Currently, I am using Python version 2.6.6 To install Pandas, I used the following command: pip install pandas Upon successful installation, I received the following message: Building wheels for collected packages: pandas Running setup.py bdist_wheel ...

Parsing JSON schemas in C#

I have been working on creating my own JSON-to-POCO framework. The approach I have taken involves defining a Json-schema class structured like this: public class JsonSchema { public string type { get; set; } public string title { get; set; } ...

Rearranging and renaming files

Hello there, I am working on a program that automatically renames files in a directory by adding a specific prefix. However, the ordering gets mixed up after renaming and I need to sort them based on the date and time information present in the original f ...

Adornments and method within a class

I'm currently facing an issue in understanding why a specific scenario is happening. I have a decorator that simply checks if a function is a method or not. Despite thinking I have a clear grasp on what a method is in Python, it seems that I may be mi ...

"Can you guide me on the steps to include a salesperson in the invoice printout in Odoo V11.0? Also, could you please

As a beginner in Odoo, I am looking to include the salesperson's name on the invoice like shown in this image, and have it displayed on the invoice PDF printout. Can anyone advise me on which file to edit in the Odoo system? Also, how can I successful ...