using Python to generate a C string literal of JSON

你说的曾经没有我的故事 提交于 2019-12-06 17:48:24

A C string starts with a quote and ends with a quote, has no embedded nulls, has all embedded quotes escaped with backslash, and all embedded backslash literals are doubled.

So take your string, double the backslashes and escape the quotes with a backslash. I think your code is exactly what you need:

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

Alternatively, you could go for this slightly less robust version:

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)) + '"'

I'd love to use string.maketrans() but a translation table can map a character to at most a single character.

David Cary

Your original suggestion and the answer from hughdbrown looks correct to me, but I've found a slightly shorter answer:

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

test script:

>>> 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\"}"

which looks like exactly the proper C string you want.

(Fortunately Python's "json.dumps()" passes forward-slashes straight through without change -- unlike some JSON encoders that prefix each forward-slash with a backslash. Such as the one described at Processing escaped url strings within json using python ).

Maybe this is what you want:

repr(json.dumps(mydict))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!