将str转换为dict

时间:2018-09-08 15:37:58

标签: python json windows python-3.x

我知道这个问题已经被提出并回答了,我尝试了其中的一些,但是在我的项目中没有一个起作用

json.load / json.load / ast / demjson都给我文件错误:

file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.txt").read()
file = ast.literal_eval(file)

Traceback (most recent call last):
  File "D:\Code\Python 5.5.4\Programmes\Messagerie\client.py", line 93, in <module>
    file = ast.literal_eval(file)
  File "D:\Code\Python 5.5.4\lib\ast.py", line 46, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "D:\Code\Python 5.5.4\lib\ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 0

Traceback (most recent call last):
  File "D:\Code\Python 5.5.4\Programmes\Messagerie\client.py", line 93, in <module>
    file = json.loads(file)
  File "D:\Code\Python 5.5.4\lib\json\__init__.py", line 319, in loads
    return _default_decoder.decode(s)
  File "D:\Code\Python 5.5.4\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "D:\Code\Python 5.5.4\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Traceback (most recent call last):
  File "D:\Code\Python 5.5.4\Programmes\Messagerie\client.py", line 93, in <module>
    file = demjson.decode(file)
  File "D:\Code\Python 5.5.4\lib\site-packages\demjson.py", line 5699, in decode
    return_stats=(return_stats or write_stats) )
  File "D:\Code\Python 5.5.4\lib\site-packages\demjson.py", line 4915, in decode
    raise errors[0]
demjson.JSONDecodeError: No value to decode

我不明白为什么json.loads / ast / demjson都可以在我的解释器上工作?

1 个答案:

答案 0 :(得分:0)

我设法使其正常工作,但我不知道为什么它不起作用

file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.txt").read()
file = ast.literal_eval(file)

也不

file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.txt")
file = ast.literal_eval(file.read())

但与之合作

file = open("C:/Users/" + getpass.getuser() + "/Wiappro/name.json")
read = file.read()
read = ast.literal_eval(read))

我希望它对其他人有用