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

goqiplq2  于 2024-01-09  发布在  其他
关注(0)|答案(1)|浏览(151)

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

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

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

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


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

  1. #This works
  2. ast.literal_eval('''{'address_components': [{'long_name': 'Fairhope', 'short_name': 'Fairhope' 'types': ['locality', 'political']}...''')
  3. #This does not work
  4. ast.literal_eval(testing7)

u3r8eeie

u3r8eeie1#

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

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

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

  1. >>> x = ' {"x":\'x\'}'.strip()
  2. >>> x
  3. '{"x":\'x\'}'
  4. >>> ast.literal_eval(x)
  5. {'x': 'x'}

展开查看全部

相关问题