Reputation: 128
I have a String, but I can't decode it to a dict using ast.literal_eval
FOUND THE ERROR, ENCODE THE STRING WRONG!
The string it should convert: (Link to the google Dock) https://docs.google.com/document/d/1jGjIPEzB9j48i1LDKQ2__Nhg5OE4R_jeaGCFq_DFr2M/edit?usp=sharing
Fallback:
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
Code to convert:
item_dict = ast.literal_eval(itemInfo["tags"][2])
This generates the string:
def json_tree(tree, parent, dictionary):
tmp_key = tree.insert(parent, 'end', uid, text=key + ' [...]', value="[...]", tag=(uid, True, dictionary[key]))
I think it's because of all the backslashes but I do not know where they're coming from
Link to reproduced code on google docs: https://docs.google.com/document/d/1CDSNqi3FqgRaVUv-N5eoV5R3xxS_atbSybaYXmC5cNE/edit?usp=sharing
Can someone help me? Thanks.
Upvotes: 0
Views: 213
Reputation: 128
Sorry, that was all my fault, I decoded the start string incorrectly. Now it is properly decoded and this saves me all the rest and I can easily use ast.literal_eval(STRING) again.
Nevertheless, many thanks for your answers.
Upvotes: 1
Reputation: 523
Updated answer:
You need to clean up the source data, because its formatting is invalid, then parse it as a json string:
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)
Upvotes: 2