python - 使用 Python 生成 JSON 的 C 字符串文字

标签 python string json escaping

我有一个 Python 字典,我想将其序列化为 JSON 并转换为适当的 C 字符串,以便它包含与我的输入字典相对应的有效 JSON 字符串。我正在使用结果在 C 源文件中自动生成一行。知道了?这是一个例子:

>>> import json
>>> mydict = {'a':1, 'b': 'a string with "quotes" and \t and \\backslashes'}
>>> json.dumps(mydict)
'{"a": 1, "b": "a string with \\"quotes\\" and \\t and \\\\backslashes"}'
>>> print(json.dumps(mydict))
{"a": 1, "b": "a string with \"quotes\" and \t and \\backslashes"}

我需要生成的是以下 C 字符串:

"{\"a\": 1, \"b\": \"a string with \\\"quotes\\\" and \\t and \\\\backslashes\"}"

换句话说,我需要对调用 json.dumps(mydict) 的结果转义反斜杠和双引号。至少我认为我这样做......以下是否有效?还是我遗漏了一个明显的角落案例?

>>> s = '"'+json.dumps(mydict).replace('\\','\\\\').replace('"','\\"')+'"'
>>> print s
"{\"a\": 1, \"b\": \"a string with \\\"quotes\\\" and \\t and \\\\backslashes\"}"

最佳答案

你最初的建议和 hughdbrown 的回答在我看来是正确的,但我发现了一个稍微简短的答案:

c_string = json.dumps( json.dumps(mydict) )

测试脚本:

>>> import json
>>> mydict = {'a':1, 'b': 'a string with "quotes" and \t and \\backslashes'}
>>> c_string = json.dumps( json.dumps(mydict) )
>>> print( c_string )
"{\"a\": 1, \"b\": \"a string with \\\"quotes\\\" and \\t and \\\\backslashes\"}"

这看起来正是您想要的正确 C 字符串。

(幸运的是,Python 的“json.dumps()”直接传递正斜杠而不做任何更改——不像某些 JSON 编码器在每个正斜杠前加上反斜杠。 例如 Processing escaped url strings within json using python 中描述的那个).

关于python - 使用 Python 生成 JSON 的 C 字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000678/

相关文章:

python - 在 Django 中使用 shell

python - 使用 ModelForms 时如何更新已存在的行?

python - 分配给逻辑索引 Numpy 数组

c++ - C函数反转char数组字符串

asp.net-mvc - ASP.NET MVC 读取原始 JSON 发布数据

python - 在全局变量上运行文件

java - 用户输入字符串而不是整数

java如何显示用户输入字符串中的所有元音

javascript - 如何将变量传递到 Magento 中的 Data.php 中?

jquery - $.ajax 解析错误 {"vErrorsFound":true ,"vMessage" :"Login Failed"}