Skip to content

Add ensure_ascii option #1689

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open

Add ensure_ascii option #1689

wants to merge 2 commits into from

Conversation

Viicos
Copy link
Member

@Viicos Viicos commented Apr 11, 2025

Change Summary

Part of pydantic/pydantic#11202.

Related issue number

Checklist

  • Unit tests for the changes exist
  • Documentation reflects the changes where applicable
  • Pydantic tests pass with this pydantic-core (except for expected changes)
  • My PR is ready to review, please add a comment including the phrase "please review" to assign reviewers

Copy link

codspeed-hq bot commented Apr 11, 2025

CodSpeed Performance Report

Merging #1689 will not alter performance

Comparing ensure-ascii (5c32b10) with main (52e9a53)

Summary

✅ 157 untouched benchmarks

};
}

#[allow(clippy::needless_lifetimes)]
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like a false positive from Clippy? There are already a bunch.

@D-stefaang
Copy link

D-stefaang commented May 5, 2025

Any chance you'd follow the core python default ensure_ascii=true here? That'd be a breaking change so that's unlikely.
Maybe a mention in the documentation?
https://docs.python.org/3/library/json.html#json.dump

FYI, the httpx library handles unicode nicely, the underlying requests library doesn't... unless explicitly sending UTF-8 bytes.

In [8]: import httpx

In [9]: data = g.model_dump_json()

In [10]: httpx.post('https://httpbin.org/post', data=data)
[info     ] HTTP Request: POST https://httpbin.org/post "HTTP/1.1 200 OK" [httpx]
Out[10]: <Response [200 OK]>

In [11]: import requests

In [12]: requests.post('https://httpbin.org/post', data=data)
---------------------------------------------------------------------------
UnicodeEncodeError 
...
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 110-111: Body ('湫莓') is not valid Latin-1. Use body.encode('utf-8') if you want to send it encoded in UTF-8.

In [13]: requests.post('https://httpbin.org/post', data=data.encode())
Out[13]: <Response [200 OK]>

@Viicos
Copy link
Member Author

Viicos commented May 5, 2025

Any chance you'd follow the core python default ensure_ascii=true here?

This can only be done in Pydantic V3, and still I don't know if the motivation is strong enough to do the change.

@Viicos Viicos requested a review from davidhewitt June 5, 2025 13:31
@@ -363,6 +364,8 @@ class SchemaSerializer:
Arguments:
value: The Python object to serialize.
indent: If `None`, the JSON will be compact, otherwise it will be pretty-printed with the indent provided.
ensure_ascii: If `True`, the output is guaranteed to have all incoming non-ASCII characters escaped.
If `False` (the default), these characters will be outputted as-is.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
If `False` (the default), these characters will be outputted as-is.
If `False` (the default), these characters will be output as-is.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Took the wording verbatim from the stdlib json module, but seems like output is by far the most common.

Comment on lines 440 to 448
for ch in fragment.chars() {
if ch.is_ascii() {
writer.write_all(ch.encode_utf8(&mut [0; 4]).as_bytes())?;
} else {
for escape in ch.encode_utf16(&mut [0; 2]) {
write!(writer, "\\u{escape:04x}")?;
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A couple of thoughts here:

So I came up with this algorithm:

let mut out = Vec::new();
let mut input = "What does 😮💨 this emoji mean?😮";
while let Some((idx, non_ascii_char)) = input
    .chars()
    .enumerate()
    .find(|(_, c)| !c.is_ascii())
{
    if idx > 0 {
        // write all ascii characters before the non-ascii one
        let ascii_run = &input[..idx];
        out.write_all(ascii_run.as_bytes()).unwrap();
    }
    
    let codepoint = non_ascii_char as u32;
    if codepoint < 0xFFFF {
        // write basic codepoint as single escape
        write!(out, "\\u{codepoint:04x}").unwrap();
    } else {
        // encode extended plane character as utf16 pair
        for escape in non_ascii_char.encode_utf16(&mut [0; 2]) {
            write!(out, "\\u{escape:04x}").unwrap();
        }
    }
    
    input = &input[(idx + non_ascii_char.len_utf8())..];
    
}
// write any ascii trailer
out.write_all(input.as_bytes()).unwrap();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants