Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

239
Visualizações
How to convert JS object to string representing a valid Python dict?

I need to write code that takes a JavaScript object and writes out a string that is a valid, nice-looking Python3 dict. If possible, I wish to do this with no external dependencies.

My current implementation is as follows:

const TRUE_PLACEHOLDER = "__replace_me_true__";
const FALSE_PLACEHOLDER = "__replace_me_false__";
const booleanToPlaceholderReplacer = (key, val) =>
  val === true ? TRUE_PLACEHOLDER : val === false ? FALSE_PLACEHOLDER : val;

const objToPythonDictStr = (obj) =>
  JSON.stringify(obj, booleanToPlaceholderReplacer, 4)
    .replaceAll(`"${TRUE_PLACEHOLDER}"`, "True")
    .replaceAll(`"${FALSE_PLACEHOLDER}"`, "False");

An example result of objToPythonDictStr demonstrating that it seems to work well:

>>  console.log(objToPythonDictStr({foo: 1, bar: false, baz: { baz2: true }}))

{
    "foo": 1,
    "bar": False,
    "baz": {
        "baz2": True
    }
}

(Note: one obvious issue with my code is that if either of the placeholder strings are used as actual strings in the data, they'll get replaced incorrectly. This is quite unlikely in my use case and I'm okay with that risk, but I'm open to a better implementation which would remove this flaw if it doesn't lead to a much more complex implementation.)

Assuming that the object passed to objToPythonDictStr is a JSON-serializable object, is my objToPythonDictStr reasonable and correct?

Specifically, are there any incompatibilities in the output of JSON serialization and Python dict syntax, other than boolean representation, which will cause issues when using the hacky methodology shown above?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Python already offers a json.loads(str) method for parsing valid JSON strings into Python objects, there is no reason to do it JS-side.

At least one thing your function is missing is the difference between null value in JSON strings and Python equivalent of None

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda