如何将JS对象转换为代表有效python dict的字符串?
我需要编写使用JavaScript对象的代码,并写出一个有效,看起来不错的Python3 dict的字符串。如果可能的话,我希望没有外部依赖性这样做。
我当前的实现如下:
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");
的示例结果表明它似乎很好:
>> console.log(objToPythonDictStr({foo: 1, bar: false, baz: { baz2: true }}))
{
"foo": 1,
"bar": False,
"baz": {
"baz2": True
}
}
objTopyThondictStstr
数据,它们将不正确地更换。更复杂的实现。)
假设对象传递给objTopyThondictStr
是一个可JSON-Serializable对象,我的objTopyThondictstr
合理且正确吗?
具体来说,除布尔表示外,在JSON序列化和Python dict语法的输出中是否有任何不兼容,在使用上面显示的hacky方法时会引起问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Python 已经提供了一个 json.loads(str) 方法来将有效的 JSON 字符串解析为 Python 对象,没有理由在 JS 端执行此操作。
您的函数至少缺少一件事是 JSON 字符串中的 null 值与 Python 等效的 None 之间的区别
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