-1

I have list like string retuned from AJAX post request:

["{'id': '1',  'name': 'John'}","{'id': '2',  'name': 'Paul'}"] 

I have used ast.literal_eval() but raises exception:

 raise ValueError('malformed node or string: ' + repr(node))
> 
> ls_j = request.form['journal_to_match']\
 ls_j= ast.literal_eval(ls_j)

What is the best way to convert to list of dictionary?

AMC
  • 2,642
  • 7
  • 13
  • 35
Arif
  • 49
  • 1
  • 9
  • 1
    An AJAX request likely returns JSON. Try `import json;json.loads(ls_j)`. – tdelaney Aug 10 '20 at 17:59
  • 1
    If you're going to use `ast.literal_eval` Don't use it on the entire list. Use it on the strings in the list. `[literal_eval(s) for s in data]` – Jab Aug 10 '20 at 18:13
  • Please provide a [mcve], as well as the entire error output. – AMC Aug 10 '20 at 22:21

4 Answers4

2

It seems your strings are JSON formatted. You could simply do:

import json

dict_list = [json.loads(s) for s in strings_list]
1

It is JSON response you are getting from API call. You can use json library to parse the data.

import json
# dataList = ['{"id": "1",  "name": "John"}','{"id": "2",  "name": "Paul"}']
dataList = request.form['journal_to_match']
json_data = [json.loads(data) for data in dataList]
print(json_data)
Krunal Sonparate
  • 1,122
  • 10
  • 29
0

Try the following

>>> import json

>>> ls_j = request.form['journal_to_match']
>>> [json.loads(e) for e in ls_j]
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
-1

so you hold a list of strings and want each element to evaluated to a dict? just do the following:

res_list = [eval(dict_string) for dict_string in ls_j]

eval() will read any string and perform it as if a user had typed it

Nano Byte
  • 106
  • 3
  • `eval` is not a good suggestion. It's unsafe. But `ast.literal_eval` is a safe alternative. – Jab Aug 10 '20 at 18:10
  • Thanks @NanoByte & @Jab. it works with ast.literal_eval , `res_list = [ast.literal_eval(dict_string) for dict_string in ls_j]` – Arif Aug 11 '20 at 02:50
  • [`why-is-using-eval-a-bad-practice`](https://stackoverflow.com/a/1832957/4985099) – sushanth Aug 11 '20 at 16:41