Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!