[Python] Can I return a single backslash in a JSON response in FastAPI?

Discussão em 'Python' iniciado por Stack, Maio 21, 2025.

  1. Stack

    Stack Membro Participativo

    Seems like a really simple question and it's not clear what the correct answer is here.

    We understand that backslashes are a special delimiter in JSON.

    From our database we're being returned a field with a backslash in it. It has to be a single backslash for contractual/legal/government representation reasons. Yet, it seems to be impossible to return just a single backslash. Wondering if this is a rule from JSON? It might be, but 3 of us for spending a day searching can't find out what's going on here.

    Here is the FastAPI app:

    from fastapi import FastAPI

    app = FastAPI()


    @app.get("/")
    async def root():
    return {
    "backslash_1": " \ ",
    "backslash_2": " \\ ",
    "backslash_3": " \\\ ",
    "backslash_4": " \\\\ ",
    "backslash_5": " \\\\\ ",
    "backslash_6": " \\\\\\ ",
    }



    Here's the JSON response:

    {
    "backslash_1":" \\ ", <-- there are 2
    "backslash_2":" \\ ",
    "backslash_3":" \\\\ ", <-- there are 4
    "backslash_4":" \\\\ ",
    "backslash_5":" \\\\\\ ", <-- there are 6
    "backslash_6":" \\\\\\ "
    }


    We're not talking about python r'' or repr() or print, we talking about JSON body response from an API. This question strictly relates to API JSON bodies, so these other SO questions aren't useful here:


    We've tried all these but this is not really helpful for our API client users, as they're seeing JSON property value string returned as "ref\\\\official", which is an erroneous response, because the official string should be "ref\official".

    The actual advice on whether it's possible or not to return a single slash would be really helpful.

    Continue reading...

Compartilhe esta Página