繁体   English   中英

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

[英]using Python to generate a C string literal of JSON

我在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编码器在每个正斜杠前加上反斜杠不同。例如在使用python处理json中转义的url字符串中描述的那样)。

AC字符串以引号开头,以引号结尾,没有嵌入的null,所有嵌入的引号都以反斜杠转义,并且所有嵌入的反斜杠文字均加倍。

因此,请使用您的字符串,将反斜杠加倍,并使用反斜杠将引号转义。 我认为您的代码正是您所需要的:

s = '"' + json.dumps(mydict).replace('\\', r'\\').replace('"', r'\"') + '"'

另外,您可以选择功能稍强的版本:

def c_string(s):
    all_chars = (chr(x) for x in range(256))
    trans_table = dict((c, c) for c in all_chars)
    trans_table.update({'"': r'\"', '\\': r'\\'})
    return "".join(trans_table[c] for c in s)

def dwarf_string(d):
    import json
    return '"' + c_string(json.dumps(d)) + '"'

我很想使用string.maketrans()但是转换表最多可以将一个字符映射到单个字符。

也许这就是您想要的:

repr(json.dumps(mydict))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM