简体   繁体   English

如何将 JS object 转换为表示有效 Python dict 的字符串?

[英]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.

相关问题 将代表对象的字符串转换为javascript对象 - Convert string representing object to javascript object 如何将表示时间点的日期对象转换为表示 moment.js 中时间部分为零的日期的日期对象 - How to convert a date object representing a point in time to a date object representing a day with zeroed time parts in moment.js 将 sql 对象转换为 node.js 中的有效 Json 字符串 - Azure - Convert sql object to valid Json string in node.js - Azure 如何将js日期时间字符串转换为python日期时间对象 - How to convert js datetime string into python datetime object 如何在python中将网页表数据转换为json对象或dict - How to convert webpage table data to json object or dict in python 如何使用JS将表示日期的字符串转换为符合ISO 8601的标准? - How can I convert this string representing a Date into an ISO 8601 compliant using JS? 将字符串转换为有效的json对象 - Convert a string to a valid json object JS:如何将字符串转换为JS对象(**不**转换为JSON)? - JS : how to convert a string to JS Object (**NOT** to JSON)? 如何将 jsPDF object 转换为有效的 base64 字符串 - How to convert jsPDF object to a valid base64 string 将字符串转换为JS对象 - Convert string to JS object
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM