0

I have a string like

res_string= '[\n  "admin_name",\n  "admin_pass",\n  "https://google.com",\n  "managed_acc_id"\n]'

Now I want to convert this into a list(say res_list) such that I can retrieve admin_name, admin_pass, etc as an index.

I.e.

res_list[0]='admin_name'
res_list[1]='admin_pass'
res_list[2]='https://google.com'
res_list[3]='managed_acc_id'

One way to achieve this is to use split/replace logic.

What will the best way to accomplish this?

Mukul Kumar
  • 564
  • 1
  • 5
  • 24

1 Answers1

2

Best is to use liter_eval from ast:

>>> import ast
>>> res_string= '[\n  "admin_name",\n  "admin_pass",\n  "https://google.com",\n  "managed_acc_id"\n]'
>>> ast.literal_eval(res_string)
['admin_name', 'admin_pass', 'https://google.com', 'managed_acc_id']

or loads from json:

>>> import json
>>> json.loads(res_string)
['admin_name', 'admin_pass', 'https://google.com', 'managed_acc_id']
Yevhen Kuzmovych
  • 10,940
  • 7
  • 28
  • 48
  • Could you explain why that would be the best option? – Sabsa Aug 02 '22 at 10:39
  • @Sabsa Because it's safe (comparing to `eval()`), simple and explicit (comparing to the split/replace solution) – Yevhen Kuzmovych Aug 02 '22 at 10:49
  • Yes, but here is an answer that compares execution time and it is not fast compared to json or no import at all. So again, what would make literal_eval the _best_ option? https://stackoverflow.com/a/55931430/10557420 – Sabsa Aug 02 '22 at 10:50
  • @Sabsa This answer compares execution times of 100k executions. I believe OPs problem is noticeably smaller hence the difference between `liter_eval`, `json` and split/replace is negligible in regards to execution time. Yes, `json` solution might be as good in this case, I'll add it to the answer. – Yevhen Kuzmovych Aug 02 '22 at 12:53