0

I am trying to convert string representation of list containing namedtuples into normal list.

Tried eval_literal, json.loads and split.

Error with ast.literal_eval

ValueError: malformed node or string: <_ast.Call object at 0x7f834bef5860>

After adding double quotes to string

SyntaxError: invalid syntax

Error with json.loads()

json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)

Problem with split is it is converting data types of contents of the namedtuple.

Please suggest me possible solution. input :

'[milestone(id=1, amount=1000, curency='inr'), milestone(id=1, amount=1000, curency='inr')]'
type<str>

expected output:

[milestone(id=1, amount=1000, curency='inr'), milestone(id=1, amount=1000, curency='inr')]
type<list>
Junior_K27
  • 151
  • 1
  • 9

1 Answers1

0

This looks like a job for eval() (StackOverflow thread about eval):

from collections import namedtuple

str = "[milestone(id=1, amount=1000, currency='inr'), milestone(id=1, amount=1000, currency='inr')]"

milestone = namedtuple('milestone', 'id amount currency')
list = eval(str)
print(list)

Try it online!

By the way, two r in currency ;)

aloisdg
  • 22,270
  • 6
  • 85
  • 105
  • I read in most of the articles that eval is dangerous. Is it safe to use eval? – Junior_K27 Sep 05 '19 at 13:34
  • If you control the input, you should be fine. In most case, I would avoid using eval. What the best solution here? Serialize the original output to a well defined format (json, xml, whatever) and deserialize it with Python for usage. Another solution would be to build your own nametuple parser. – aloisdg Sep 05 '19 at 14:35