'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?



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1