在Python中 Websocket这样给我字符串:
'{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}'
我想将此字符串转换为表格:
{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}
似乎唯一的区别是开头和结尾的撇号。 有关如何做到这一点的任何想法?
答案 0 :(得分:1)
import json
def StringToJson(string):
# [1:-1] Assuming you only want to remove the quotes at either end. Strip()
#because there might after all be some whitespace present.
return json.loads(string.strip()[1:-1])
string = """'{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}'"""
table = StringToJson(string)
如果上述解决方案不起作用,可能只是您认为存在的引号只是您获得的错误消息的一部分。您可以尝试以下方法:
import json
parsedString = json.loads(string) # Where string is the text you're trying to access the keys of.
答案 1 :(得分:0)
import ast
ast.literal_eval('{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}')
答案 2 :(得分:0)
看起来你正在获得一个json对象。您可以使用内置于json转换器中的python将其转换为python dict。
import json
t = json.loads('{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}')
t
现在将成为具有这些键/值对的字典
有关更多示例,请参阅此页面。 https://docs.python.org/2/library/json.html