0

I have a string that looks like this:

'{"screen_name":"Brian","avatar":1},{"screen_name":"David","avatar":21},{"screen_name":"Teo","avatar":34}'

How can I make it a list of dictionaries? I tried with json.loads, but it threw an error...

Ziv Sion
  • 424
  • 4
  • 14
  • You need to add square brackets to the string, `'[{"screen_name":...}]'` – Guy Jun 19 '22 at 10:00
  • 1
    It doesn't represent a list in any notation. At best this is a tuple of dicts as a Python literal. For valid JSON or a Python list literal, it's missing the `[]`. – deceze Jun 19 '22 at 10:01
  • you can use `eval` (or better to use `ast.literal_eval`, definitely if the source is untrusted). This will give you a *tuple* of dictionaries. If you must have a list, just convert that tuple to a list. But you should generally change whatever process is creating this sort of string to use an actual serialization format – juanpa.arrivillaga Jun 19 '22 at 10:42

1 Answers1

1

before trying json.loads, you have to make sure that is surrounded by square brackets.

You can achieve that by using format or fstrings, so you can do:

>>> import json
>>> json.loads(f"[{original}]")
[{"screen_name":"Brian","avatar":1},{"screen_name":"David","avatar":21},{"screen_name":"Teo","avatar":34}]
XxJames07-
  • 1,833
  • 1
  • 4
  • 17