[英]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.我需要编写代码,它采用 JavaScript object 并写出一个有效、美观的 Python3 字典字符串。 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: objToPythonDictStr
的示例结果表明它似乎运行良好:
>> 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?假设传递给
objToPythonDictStr
的 object 是一个 JSON 可序列化的 object,那么我的objToPythonDictStr
合理正确?
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?具体来说,JSON 序列化的 output 和 Python dict 语法中是否存在任何不兼容性,而不是 boolean 表示,这会在使用上面显示的 hacky 方法时引起问题?
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. Python 已经提供了一个
json.loads(str)
方法来将有效的 JSON 字符串解析为 Python 对象,没有理由在 JS 端这样做。
At least one thing your function is missing is the difference between null value in JSON strings and Python equivalent of None您的 function 至少缺少一件事是 JSON 字符串中的 null 值与相当于 None 的 Python 之间的差异
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.