-1

I'm getting a json with some items, and one of them can come in a list format inside a string, for example:

jsonresp = {
    "number":1,
    "size":17,
    "totalPages":1,
    "numberOfElement":17,
    "totalElements":"17",
    "accounts":"['123', '456', '789']"
}

putting the account attribute in a variable, I wanted to receive it in a list format and not a string. I tried as follows but it doesn't work:

accounts = list(jsonresp["accounts"])

I managed to do it using replace the characters [ and ], and then doing a comma split, but if there is a string with a comma, I may have problems. I wanted to know if there was a more direct way to do it.

1 Answers1

1

Did you try ast.literal_eval()?

accounts = ast.literal_eval(jsonresp["accounts"])

Sould output:

['123', '456', '789']
Jamiu S.
  • 5,257
  • 5
  • 12
  • 34