繁体   English   中英

我无法将生成的字符串解码为 Python dict

[英]I can not decode generated string to Python dict

我有一个字符串,但我无法使用ast.literal_eval将其解码为字典

发现错误,编码错误的字符串!

它应该转换的字符串:(链接到 google Dock) https://docs.google.com/document/d/1jGjIPEzB9j48i1LDKQ2__Nhg5OE4R_jeaGCFq_DFr2M/edit?usp=sharing

倒退:

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:/Users/user/Documents/Python/Documents/pickle_viewer/PickleViewer.py", line 444, in selectItem
    item_dict = ast.literal_eval(itemInfo["tags"][2])
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1

要转换的代码:

item_dict = ast.literal_eval(itemInfo["tags"][2])

这会生成字符串:

    def json_tree(tree, parent, dictionary):
                tmp_key = tree.insert(parent, 'end', uid, text=key + ' [...]', value="[...]", tag=(uid, True, dictionary[key]))

我认为这是因为所有的反斜杠,但我不知道它们来自哪里

链接到谷歌文档上的复制代码: https://docs.google.com/document/d/1CDSNqi3FqgRaVUv-N5eoV5R3xxS_atbSybaYXmC5cNE/edit?usp=sharing

有人能帮我吗? 谢谢。

更新的答案:

您需要清理源数据,因为它的格式无效,然后将其解析为 json 字符串:

Python 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)] on win32
import json
source = <your_very_long_input_loaded_as_raw_string_comes_here>
source = source.replace('\\', '')
source = source.replace('\'', '"')
source = source.replace('} {"comments"', '}, {"comments"')
source = "[" + source + "]"
d = json.loads(source)

抱歉,这都是我的错,我错误地解码了起始字符串。 现在它已正确解码,这为我节省了所有 rest,我可以轻松地再次使用 ast.literal_eval(STRING)。

不过,非常感谢您的回答。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM