【发布时间】:2021-12-28 22:53:59
【问题描述】:
我正在为技术用户编写一些代码,以便在 JSON 中传递变量的占位符,并附带一个定义每个变量的字典。我想用这些值替换这些变量,最终需要将其放入 Python 字典中。想象一下,我从这个开始:
>>> json_in = """
{
"sidebar": {
"type": "sidebar",
"title": "<h1>Vulnerability Data</h1>",
"description": {md_html}
},
"widgets": [
{
"name": "Map",
"itemId": {item_id},
"showNavigation": false
}
]
}"""
>>> args = {'md_html': '<super_long_html_string>', 'item_id': 'abcdef12345'}
如果我尝试使用json_in.format(**args) 之类的格式,我只会在遇到第一个左大括号(“侧边栏”之前)时收到 KeyError,该格式会尝试读取。将花括号加倍会在format() 中转义它们,但是这个 JSON 可能有数千行长,所以我真的不想让人们做大量的重新格式化。我想我可以尝试在format() 之前使用 Python 编辑 JSON。我必须避免从格式化字符串中破坏花括号,所以这似乎变得不必要的复杂。 Python通常有简单的解决方案,那我错过了什么?
我走的另一条路是首先将其创建为 Python dict。很容易搜索 JSONisms 并替换为 Python 等效项(例如:false 到 False、true 到 True)。我没有格式化字符串 ({item_id}),而是使用变量 (item_id) 来结束这样的事情:
>>> md_html = '<super_long_html_string>'
>>> item_id = 'abcdef12345'
>>> dict_in = {
"sidebar": {
"type": "sidebar",
"title": "<h1>Vulnerability Data</h1>",
"description": md_html
},
"widgets": [
{
"name": "Map",
"itemId": item_id,
"showNavigation": False
}
]
}
问题是变量md_html 和item_id 在这个例子中是硬编码的,我想接受用户传入的任何内容(参见上面的args dict)。如果我可以创建一个带有占位符的字典并用提供的输入替换它们,那将解决我的问题。
【问题讨论】:
-
一般用字符串格式化,要处理特殊字符。例如,
{和}对应于.format。其他选项是模板docs.python.org/3/library/string.html#template-strings 或老派%格式在这种情况下可能更自然使用。
标签: python json dictionary format