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)
7
  • 2
    For the record, @Ch3steR's solution is safer and I do prefer that one. Commented Mar 20, 2020 at 8:13
  • 1
    Check this blog post of Ned Batchelder Eval really dangerous Commented Mar 20, 2020 at 8:16
  • 3
    @Ch3steR I have removed my answer and upvoted yours so that we can promote safer practices. Commented Mar 20, 2020 at 8:16
  • 3
    @dspencer Yes, for the community. ;) Thanks for the up. Commented Mar 20, 2020 at 8:19
  • 1
    You might want look at this @learner eval vs ast.literal_eval Commented Mar 20, 2020 at 8:22

2 Answers 2

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']
Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.