json 将一个字符串变量传递给具有前导空格的ast.literal_eval

goqiplq2  于 5个月前  发布在  其他
关注(0)|答案(1)|浏览(48)

我有一个变量,它存储包含单引号和双引号的字符串。例如,一个变量testing7是以下字符串:

{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...

字符串
我需要通过ast.literal_eval传递这个变量,然后是json.dumps,最后是json.loads。然而,当我试图通过ast.literal传递它时,我得到一个错误:

line 48, in literal_eval
node_or_string = parse(node_or_string, mode='eval')
line 35, in parse
  return compile(source, filename, mode, PyCF_ONLY_AST)
File "<unknown>", line 1
{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...' 
^
IndentationError: unexpected indent


如果我将字符串复制并传递到literal_eval中,如果用三重引号括起来,它将工作:

#This works
ast.literal_eval('''{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...''')

#This does not work
ast.literal_eval(testing7)

u3r8eeie

u3r8eeie1#

看起来这个错误与引号无关。错误的原因是字符串前面有空格。例如:

>>>ast.literal_eval("   {'x':\"t\"}")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/leo/miniconda3/lib/python3.6/ast.py", line 48, in literal_eval
    node_or_string = parse(node_or_string, mode='eval')
  File "/home/leo/miniconda3/lib/python3.6/ast.py", line 35, in parse
    return compile(source, filename, mode, PyCF_ONLY_AST)
  File "<unknown>", line 1
    {'x':"t"}
    ^
IndentationError: unexpected indent

字符串
在将字符串传递给函数之前,你可能想去掉它。此外,我在你的代码中没有看到混合的双引号和单引号。在单引号字符串中,你可能想使用\来转义单引号。例如:

>>> x = '    {"x":\'x\'}'.strip()
>>> x
'{"x":\'x\'}'
>>> ast.literal_eval(x)
{'x': 'x'}

相关问题