2

I have a string:

str = '[\'RED\', \'GREEN\', \'BLUE\']'

I want to parse it to

list = ['RED','GREEN','BLUE']

But, I am unable to do so.

I tried to parse using json.loads:

json.loads(str)

It gave me:

{JSONDecodeError}Expecting value: line 1 column 2 (char 1)
Ch3steR
  • 19,076
  • 4
  • 25
  • 52
learner
  • 4,132
  • 6
  • 45
  • 95

2 Answers2

5

You can use ast.literal_eval. eval can be dangerous on untrusted strings. You ast.literal_eval which evaluates only valid python structures.

import ast
s = '[\'RED\', \'GREEN\', \'BLUE\']'
ast.literal_eval(s)
# ['RED', 'GREEN', 'BLUE']
dspencer
  • 3,898
  • 4
  • 19
  • 41
Ch3steR
  • 19,076
  • 4
  • 25
  • 52
0

You can use python's in-built function eval(). This works for conversion to python's other default data structures(dict, tuples, etc) as well. Something like:

str = '[\'RED\', \'GREEN\', \'BLUE\']'
l = eval(str)
windstorm
  • 315
  • 2
  • 10