如何将python包含嵌套字典的字符串转换为字典?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (485)

我正在尝试将包含嵌套字典的字符串(作为字符串)转换为python字典。我试着用ast和json来做它,它们都给了我错误的WRTEOL。我还有别的办法可以做到吗?

下面是示例字符串:

string = "
    {"akka":
        {"loggers":["akka.ent4jLogger"],
         "logging-filter":"akka.LoggingFilter",
         "loglevel":"INFO"},
     "awt":{"toolkit":"XToolkit"}, 
           .....
           {"password":"hmm","username":"read"},
     "schemaPrefix":"test","username":"load"}}}
    }"

请注意,我只粘贴了字符串的开始和结束,.不是字符串的实际部分。

我需要将该字符串转换为Pythondict,以便解析其中的值。

分别使用json和ast时出现的错误:

json -

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/__init__.py", line 339, in loads
    return _default_decoder.decode(s)
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 364, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 380, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Invalid control character at: line 1 column 13530 (char 13529)

ast-

Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 49, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/ast.py", line 37, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
SyntaxError: EOL while scanning string literal
提问于
用户回答回答于

你的json字符串可能包含回车(\r)或换行符(\n)在他们身上。

import json
json.loads(string.replace('\r', '').replace('\n', '') 

import json
json.loads(string.replace('\r', '\\r').replace('\n', '\\n') 

扫码关注云+社区

领取腾讯云代金券