2

我正在尝试将此字符串转换为python dict:

q = '{"request_body": "{\\x22username\\x22:\\x222\\x22,\\x22password\\x22:\\x226\\x22,\\x22id\\x22:\\x22e2cad174-736e-3041-cf7e\\x22, \\x22FName\\x22:\\x22HS\\x22}", "request_method": "POST"}'

当我这样做json.loads(a)时给我一个错误simplejson.decoder.JSONDecodeError: Invalid \escape: line 1 column 19 (char 19)。所以比我决定转换\x22". 我遵循了这个问题的建议。

>>> q.decode('string_escape')
'{"request_body": "{"username":"2","password":"6","id":"e2cad174-736e-3041-cf7e", "FName":"HS"}", "request_method": "POST"}'
>>> 

但之后那"{"部分就无效了。所以我的问题是将字符串q转换为python dict的可能方法是什么?

4

1 回答 1

9

The problem is that JSON doesn't support the \xNN escape, only \uNNNN. Replacing \x22 with " will make the JSON invalid. What you should do is to replace \xNN with \u00NN:

>>> q = q.replace('\\x', '\\u00')
>>> json.loads(q)
{'request_body': '{"username":"2","password":"6","id":"e2cad174-736e-3041-cf7e", "FName":"HS"}', 'request_method': 'POST'}

(Note: This is not a complete solution as it will erratically replace correctly-escaped strings like abc\\xyz to abc\\u00yz. A complete solution probably needs a regex or even a lexer.)

于 2013-08-14T13:34:06.673 回答