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

时间:2019-10-04 12:18:21

标签: python dictionary pickle fallback

我有一个字符串,但无法使用render() { return ( <div className="container"> <ul> {this.state.try.map(item => item.possible_persons.map(person => person.names.map((name, index) => ( <li key={index}>{name.display}</li> )) ) )} </ul> </div> ); }

将其解码为字典

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

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

回扣:

ast.literal_eval

要转换的代码:

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])

我认为这是由于所有反斜杠引起的,但我不知道它们来自何处

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

有人可以帮助我吗?谢谢。

2 个答案:

答案 0 :(得分:2)

更新后的答案:

您需要清理源数据,因为其格式无效,然后将其解析为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)

答案 1 :(得分:1)

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

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