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
  • 20,090
  • 4
  • 28
  • 58
learner
  • 4,614
  • 7
  • 54
  • 98

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
  • 4,297
  • 4
  • 22
  • 43
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
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
  • 375
  • 2
  • 10