python生成json_使用Python生成一个C字符串的JSON文字

1586010002-jmsa.png

I have a dictionary in Python that I would like to serialize in JSON and convert to a proper C string so that it contains a valid JSON string that corresponds to my input dictionary. I'm using the result to autogenerate a line in a C source file. Got it? Here's an example:

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

What I need to generate is the following C string:

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

In other words, I need to escape the backslash and double-quote on the result of calling json.dumps(mydict). At least I think I do.... Will the following work? Or am I missing an obvious corner case?

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

>>> print s

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

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值