Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

236
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda