Just decode the JSON as JSON, and then write out a new JSON document without ensuring the data is ASCII safe:

import json

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        document = json.load(input)
        json.dump(document, output, ensure_ascii=False)

From the json.dump() documentation:

If ensure_ascii is true (the default), the output is guaranteed to have all incoming non-ASCII characters escaped. If ensure_ascii is false, these characters will be output as-is.

Demo:

>>> import json
>>> print(json.loads(r'"l\u00f6yt\u00e4\u00e4"'))
löytää
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"')))
"l\u00f6yt\u00e4\u00e4"
>>> print(json.dumps(json.loads(r'"l\u00f6yt\u00e4\u00e4"'), ensure_ascii=False))
"löytää"

If you have extremely large documents, you could still process them textually, line by line, but use regular expressions to do the replacements:

import re

unicode_escape = re.compile(
    r'(?<!\\)'
    r'(?:\\u([dD][89abAB][a-fA-F0-9]{2})\\u([dD][c-fC-F][a-fA-F0-9]{2})'
    r'|\\u([a-fA-F0-9]{4}))')
def replace(m):
    return bytes.fromhex(''.join(m.groups(''))).decode('utf-16-be')

with open("input.json", "r", encoding="utf-8") as input:
    with open("output.txt", "w", encoding="utf-8") as output:
        for line in input:
            output.write(unicode_escape.sub(replace, line))

This however fails if your JSON has embedded JSON documents in strings or if the escape sequence is preceded by an escaped backslash.

Answer from Martijn Pieters on Stack Overflow
🌐
Finxter
blog.finxter.com › 4-best-ways-to-remove-unicode-characters-from-json
4 Best Ways to Remove Unicode Characters from JSON – Be on the Right Side of Change
September 30, 2023 - Sometimes, you might need or want to remove these Unicode characters from your JSON data. This can be done in various ways, depending on the programming language you are using. In Python, for instance, you could leverage the encode and decode functions to remove unwanted Unicode characters: cleaned_string = original_string.encode("ascii", "ignore").decode("utf-8") In this code snippet, the encode function tries to convert the original string to ASCII, replacing Unicode characters with basic ASCII equivalents.
Discussions

python - how to find and replace unicode in json files? - Stack Overflow
I have folder of json files (approx 70 GB data), these json files are emails. I want to open all the files and find Unicodes using python. later I want to replace those Unicodes with any regular More on stackoverflow.com
🌐 stackoverflow.com
March 31, 2021
Replace escaped Unicode chars (`\u20ac`) in stored JSON?
While chasing a Unicode-related bug, I realized that our stored JSON (on GitHub) has ugly escaped Unicode characters, e.g. in this study and this tree collection. These Unicode characters are handl... More on github.com
🌐 github.com
2
February 22, 2017
JSON unicode characters conversion - javascript
About correct json for string you ... (json supports any unicode characters in strings except " and \). Also if you need to encode some character that require more than two bytes - it will result in two escape codes for example "𩄎" would be "\ud864\udd0e" when escaped. So, If you really need to decode string above - you can fix it before decoding, replacing \uffffffe2 ... More on stackoverflow.com
🌐 stackoverflow.com
python - How to get string objects instead of Unicode from JSON - Stack Overflow
This holds especially true if your JSON structure is from the field, containing user input. Because then you probably need to walk anyway over your structure - independent on your desired internal data structures ('unicode sandwich' or byte strings only). ... Unicode normalisation. For the unaware: Take a painkiller and read this. So using the byteify recursion you kill two birds with one stone: ... In my tests it turned out that replacing ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › standard › serialization › system-text-json › character-encoding
How to customize character encoding with System.Text.Json - .NET | Microsoft Learn
May 26, 2023 - By default, the serializer escapes all non-ASCII characters. That is, it replaces them with \uxxxx where xxxx is the Unicode code of the character. For example, if the Summary property in the following JSON is set to Cyrillic жарко, the WeatherForecast object is serialized as shown in this example:
🌐
Stack Overflow
stackoverflow.com › questions › 66882358 › how-to-find-and-replace-unicode-in-json-files
python - how to find and replace unicode in json files? - Stack Overflow
March 31, 2021 - I have a dataset of emails stored as json files. the main aim is to perform tf-idf (to get high ranking words) on the dataset using pyspark. for that I need to first read and write json files in pandas df as record oriented format because that can be easily dealt in pyspark. while reading some of them I get ValueError: Unpaired high surrogate when decoding 'string' on reading json file. my idea is that the email body has unicode that is causing problem.
🌐
Yui
yui.github.io › yui2 › docs › yui_2.7.0 › docs › JSON.js.html
API: json JSON.js (YUI Library)
* @module json * @class JSON * @static */ YAHOO.lang.JSON = (function () { var l = YAHOO.lang, /** * Replace certain Unicode characters that JavaScript may handle incorrectly * during eval--either by deleting them or treating them as line * endings--with escape sequences.
🌐
GitHub
github.com › OpenTreeOfLife › peyotl › issues › 173
Replace escaped Unicode chars (`\u20ac`) in stored JSON? · Issue #173 · OpenTreeOfLife/peyotl
February 22, 2017 - If we want to restore pretty Unicode for data saved in the future, it seems to all boil down to a single call to json.dump in peyotl that's used for all JSON docs.
Author   OpenTreeOfLife
Find elsewhere
Top answer
1 of 16
188

While there are some good answers here, I ended up using PyYAML to parse my JSON files, since it gives the keys and values as str type strings instead of the unicode type. Because JSON is a subset of YAML, it works nicely:

>>> import json
>>> import yaml
>>> list_org = ['a', 'b']
>>> list_dump = json.dumps(list_org)
>>> list_dump
'["a", "b"]'
>>> json.loads(list_dump)
[u'a', u'b']
>>> yaml.safe_load(list_dump)
['a', 'b']

Notes

Some things to note though:

  • I get string objects because all my entries are ASCII encoded. If I would use Unicode encoded entries, I would get them back as unicode objects — there is no conversion!

  • You should (probably always) use PyYAML's safe_load function; if you use it to load JSON files, you don't need the "additional power" of the load function anyway.

  • If you want a YAML parser that has more support for the 1.2 version of the spec (and correctly parses very low numbers) try Ruamel YAML: pip install ruamel.yaml and import ruamel.yaml as yaml was all I needed in my tests.

Conversion

As stated, there isn't any conversion! If you can't be sure to only deal with ASCII values (and you can't be sure most of the time), better use a conversion function:

I used the one from Mark Amery a couple of times now, it works great and is very easy to use. You can also use a similar function as an object_hook instead, as it might gain you a performance boost on big files. See the slightly more involved answer from Mirec Miskuf for that.

2 of 16
146

There's no built-in option to make the json module functions return byte strings instead of Unicode strings. However, this short and simple recursive function will convert any decoded JSON object from using Unicode strings to UTF-8-encoded byte strings:

def byteify(input):
    if isinstance(input, dict):
        return {byteify(key): byteify(value)
                for key, value in input.iteritems()}
    elif isinstance(input, list):
        return [byteify(element) for element in input]
    elif isinstance(input, unicode):
        return input.encode('utf-8')
    else:
        return input

Just call this on the output you get from a json.load or json.loads call.

A couple of notes:

  • To support Python 2.6 or earlier, replace return {byteify(key): byteify(value) for key, value in input.iteritems()} with return dict([(byteify(key), byteify(value)) for key, value in input.iteritems()]), since dictionary comprehensions weren't supported until Python 2.7.
  • Since this answer recurses through the entire decoded object, it has a couple of undesirable performance characteristics that can be avoided with very careful use of the object_hook or object_pairs_hook parameters. Mirec Miskuf's answer is so far the only one that manages to pull this off correctly, although as a consequence, it's significantly more complicated than my approach.
🌐
Stack Overflow
stackoverflow.com › questions › 55956311 › remove-unicode-string-and-spaces-from-json-response
java - Remove unicode string and spaces from json response - Stack Overflow
May 2, 2019 - I have Pojo and I was trying to map Json response on the Pojo. But I think because space I was getting error. I am using Jackson. Now here what I did and it got successfully mapped retValue = retValue.replaceAll("\\\\u000d\\\\u000a\\s*", "");retValue = retValue.replace("\\", "");char ch = '\"';int posOfJ = retValue.indexOf(ch);int posOfi = retValue.lastIndexOf('\"');retValue = retValue.substring(posOfJ + 1, posOfi);signingGroupResponse = JsonUtil.convertJsonToObject(retValue, SigningGroupResponse.class); Thanks for your help 2019-05-02T17:55:43.937Z+00:00
🌐
Stack Overflow
stackoverflow.com › questions › 55871805 › how-to-replace-unicode-dicts-values-and-return-to-unicode-format-in-python
json - How to replace unicode dicts values and return to unicode format in python - Stack Overflow
Copydef replacer(df): df_final = df import unicodedata df_final['issue_state_upd'] = "" for i in range(len(df_final['issue_state'])): #From unicode to string df_final['issue_state_upd'][i] = unicodedata.normalize('NFKD', df_final['issue_state'][i]).encode('ascii','ignore') #From string to dict df_final['issue_state_upd'][i] = json.loads((df_final['issue_state_upd'][i])) #Replace value in fuel key df_final['issue_state_upd'][i].update({'fuel_type': df_final['issue_state_upd'][i]}) #From dict to str df_final['issue_state_upd'][i] = json.dumps(df_final['issue_state_upd'][i]) #From str to unicode df_final['issue_state_upd'][i] = unicode(df_final['issue_state_upd'][i], "utf-8") return df_final ·
🌐
PYnative
pynative.com › home › python › json › python encode unicode and non-ascii characters as-is into json
Python Encode Unicode and non-ASCII characters as-is into JSON
May 14, 2021 - This solution is useful when you want to dump Unicode characters as characters instead of escape sequences. Set ensure_ascii=False in json.dumps() to encode Unicode as-is into JSON
Top answer
1 of 3
2

According to the PHP documentation on stripslashes (), it

un-quotes a quoted string.

Which means, that it basically removes all backslashes, which are used for escaping characters (or Unicode sequences). When removing those, you basically have no chance to be completely sure that any sequence as "u0024" was meant to be a Unicode entity, your user could just have entered that.

Besides that, you will get some trouble when using stripslashes () on a JSON value that contains escaped quotes. Consider this example:

{
  "key": "\"value\""
}

This will become invalid when using stripslashes () because it will then look like this:

{
  "key": ""value""
}

Which is not parseable as it isn't a valid JSON object. When you don't use stripslashes (), all escape sequences will be converted by the JSON parser and before outputting the (decoded) JSON object to the client, PHP will automatically decode (or "convert") the Unicode sequences your data may contain.

Conclusion: I'd suggest not to use stripslashes () when dealing with JSON entities as it may break things (as seen in the previous example, but also in your problem).

2 of 3
2

The main question you have to understand, is why do you need to strip slashes? And, if it is really necessary to strip slashes, how to manage the encoding? Probably it is a good idea to convert unicode symbols before to strip slashes, not after, using html_entity_decode .

Anyway, you can try fix the problem with this workaround:

$string = "Hello World, I have u00249999999 dollars";
$string = preg_replace( "/u([0-9A-F]{0,4})/", "&#x$1;", $string ); // recover "u" + 4 alnums
$string = html_entity_decode( $string, ENT_COMPAT, 'UTF-8' ); // convert to utf-8
🌐
Dropbox
dropbox.com › developers › reference › json-encoding
Encoding for JSON Arguments - Developers - Dropbox
var charsToEncode = /[\u007f-\uffff]/g; // This function is simple and has OK performance compared to more // complicated ones: http://jsperf.com/json-escape-unicode/4 function http_header_safe_json(v) { return JSON.stringify(v).replace(charsToEncode, function(c) { return '\\u'+('000'+c.ch...
🌐
GitHub
gist.github.com › composite › 8396541
JSON stringify with escape unicode characters. http://stackoverflow.com/a/4901205/489575 · GitHub
JSON stringify with escape unicode characters. http://stackoverflow.com/a/4901205/489575 - json.stringify.js
🌐
Elixir Forum
elixirforum.com › questions & help › questions
Replacing ">" and "<" with Unicode code point for. json encoding - Questions - Elixir Programming Language Forum
March 29, 2022 - Hello everyone after few hours of looking at docs and googling I still can’t for the love of me figure out how to mirror the json_encode in PHP json_encode with JSON_HEX_TAG which according to documentation here convert All are converted to \u003C and \u003E.