从字符串 python 中提取 table

Extract table from string python

在Python Websocket 给我这样的字符串:

'{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}'

我想将此字符串转换为 table:

{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}

似乎唯一的区别是开头和结尾的撇号。 关于如何做到这一点有什么想法吗?

import ast
ast.literal_eval('{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}')
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.

您似乎要返回一个 json 对象。您可以使用 python 内置的 json 转换器将其转换为 python 字典。

import json
t = json.loads('{"type":"done","sequence":49109868,"time":"2015-04-06T17:57:00.86877Z"}')

t 现在将成为那些 key/value 对

的字典

有关更多示例,请参阅此页面。 https://docs.python.org/2/library/json.html