What is the best method for encoding non-ASCII characters in JSON.stringify as ASCII-safe escaped characters (\uXXXX) without the need for additional post-processing?

In order to send characters like ü to the server as unicode characters but in an ASCII-safe string format, I need them to be represented as \u00fc with 6 characters, rather than displaying the character itself. However, no matter what I try, after using JSON.stringify, it always reverts back to displaying ü.

If I attempt to input 2 backslashes like \\u00uc, then the JSON string will also display 2 backslashes which is not ideal.

An important limitation: I am unable to modify the string after using JSON.stringify due to it being a part of the framework without any available workarounds or options to fork the entire package.

Is there a way to achieve this? If so, how can it be done?

Answer №1

If you need your JSON data to be ASCII-safe, simply replace any non-ascii characters after encoding.

var data = {"name":"füßchen", "numbers": [1,2,3]}

var jsonData = JSON.stringify(data)
jsonData  = jsonData.replace(/[\u007F-\uFFFF]/g, function(character) {
    return "\\u" + ("0000" + character.charCodeAt(0).toString(16)).substr(-4)
})

document.write(jsonData);
document.write("<br>");
document.write(JSON.parse(jsonData));

Answer №2

Here is a helpful solution to achieve your desired outcome. My approach was inspired by the following question: How can I convert a Unicode string to JavaScript escape?

var obj = {"key":"ü"};
var str1 = JSON.stringify(obj);
var str2 = "";
var chr = "";
for(var i = 0; i < str1.length; i++){
    if (str1[i].match(/[^\x00-\x7F]/)){
        chr = "\\u" + ("000" + str1[i].charCodeAt(0).toString(16)).substr(-4);
    }else{
        chr = str1[i];
    }
    str2 = str2 + chr;
}  
console.log(str2)

Additionally, it may be beneficial for you to consider @t.niese's suggestion about handling this on the server side.

Answer №3

To alter how JSON.stringify behaves, you can implement a custom toJSON method for the specific scenario. More information on this can be found at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#tojson_behavior

If an object contains a function as its toJSON method, using JSON.stringify will utilize the output of that method instead of the usual serialization process. You can incorporate this technique with strategies mentioned in other solutions to achieve the desired outcome, even if a library does not offer customization options by default.

(However, keep in mind that a third-party library may potentially override this behavior.)

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

Utilize the existing code to prevent multiple form submissions

My current focus is on integrating a Delete Account feature into my website. If a user requests to delete their account (please note that it takes 3 days to completely delete the data) and tries to log in within this 3-day period, we need to prompt for co ...

How can we use jQuery to extract an HTML element's external stylesheet and add it to its "style" attribute?

My goal is to extract all CSS references from an external stylesheet, such as <link rel="stylesheet" href="css/General.css">, and add them to the existing styling of each HTML element on my page (converting all CSS to inline). The reason for this re ...

Steps for converting JSON data to an HTML table using an .each loop

I'm currently working on an ajax get request to display json data in an html table. While I have experience doing this with vanilla javascript, I decided to give jquery a shot. However, I seem to be encountering an issue within my .each loop. The synt ...

"Exploring the world of jest.doMock: A guide to mocking

Here is the code snippet I am testing: ... import data from '../data/mock.json'; // function is async export const something = async () => { try { ... if (!data) { throw 'error is here!'; } ...

What is the reason my answer for the powerset problem is flawed? Both my recursive and iterative methods are attached for review

How can I generate all possible subsets from an array of unique integers? For instance, if I have powerSet[1,2,3], the expected output should be [[], [1], [2], [3], [1,2], [1,3], [2,3], [1,2,3]] I've tried a recursive approach: function powerset(arr ...

Requesting multiple parts with Retrofit 2.0 on Android is taking an excessive amount of time

I am attempting to use Retrofit 2.0 to send a multipart request in order to upload an image to my server. Currently, I have a RequestBody that contains my image file RequestBody requestFile = RequestBody.create(MediaType.parse("image/*"), file); Next, I ...

Is there a solution for retrieving POCOs in WCF Data Services 5.0?

Excuse me if this question has been asked before, but I'm facing an issue while implementing WCF Data Services 5.0 in our application. The problem arises with service operations only being able to return primitive types, which is quite frustrating com ...

Get a single object from an array with .single method provided by @ngrx

Seeking to retrieve an Observable containing a single object from an array of objects in my store. I aim to utilize the .single operator, which should throw an exception if there is not exactly 1 object present. However, I'm struggling with this as my ...

I require assistance in converting a .textpb file to JSON format, which includes nested input structures

Can anyone assist me in converting a .textpb file to json with nested input? I have tried using various Python tools, but none of them seem to work properly as the .textpb or .pb format is nested, resulting in incorrect output data when converted to json. ...

Asynchronous operations in Node.js with Express

Hey, I'm still pretty new to using async functions and I could really use some help understanding how to pass callbacks in async.each for each item to the next level (middleware). Here's the logic: I want to iterate through all items, and if an ...

Looking for the best JSON database library?

Currently utilizing Node.js... Personally, I find SQL to be unappealing. My preference lies with JSON, as I desire to store my server data in that format. While I can utilize JSON.parse and .stringify, it seems like a suboptimal approach for larger appli ...

Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this: HTML: <div class="container" id="cont"> <div class="box show"></div> </div> CSS: .container { width: 100vw; height: 100vh; } .box { position: absolute ...

Three.js - Troubleshooting: Imported OBJ model displaying partially transparent triangles

Currently, I am encountering an issue with an obj file that was exported from Rhino3D into obj format. In this case, half of the triangles making up a certain part of the model appear to be transparent, despite appearing fine in the 3D editor. var loader ...

What distinctions can be observed between interacting with the Jira Rest API manually compared to through programming?

Just starting out with Jira Rest APIs...I'm looking to log in to my Local Jira server using a VBA program. While I can successfully access the REST API manually and receive the JSON response I need, I keep encountering an error whenever I try to do it ...

Looking to display user data within a specific div using JavaScript? Check out my code!

Issue Solved by Me I resolved the problem by using ko.js to check data binding in java! Thanks to everyone who helped. I have implemented this code to display online users in my chat application (x7chat 3, available for free download) The code can be fou ...

When serializing with Json.NET, JsonConvert.SerializeObject can include a comment in the generated output

Could you help me remove the comment that appears at the end of my generated JSON string? I am working on converting XML to JSON using Json.net. Specifically, I need to convert data from the Zillow API's XML format to a JSON string for delivery to a ...

Ways to address observables in Angular in a manner similar to deferred objects

Transitioning from AngularJS to Angular has posed a challenge for me, especially when it comes to moving from promises to observables. Below is an example of my code in AngularJS: var deferred = $q.defer(), frame = document.createElement('newFrame ...

I need to display 5 columns in a parent component, each with its own unique icon. How can I conditionally render them in a React component?

Creating a parent component to reuse multiple times can be very useful. In my case, I have included 5 different icons in each instance of the component, all taken from hero icons. I have set up an object with unique ids for each child component, but I am ...

Trouble arises when trying to load angular ui-bootstrap using require.js unless I change the name to ui.bootstrap

Code Overview: main.js: require.config({ paths: { 'uiBootstrap': '../lib/bootstrap/angular-bootstrap/ui-bootstrap-tpls.min' }, shim: {***}, priority: ['angular'], deps: ...

looking to display the latest status value in a separate component

I am interested in monitoring when a mutation is called and updates a status. I have created a component that displays the count of database table rows when an API call is made. Below is the store I have implemented: const state = { opportunity: "" } ...