0

I have a field in database of type longtext with a value like [{"A":"apple"}, {"B":"ball"} , {"c":"cat"}] i.e a list of dictionaries. So now I am fetching that from SQL database using cursor.fetchone() which returns a tuple with first element as my fetched field. so i extracted it by doing (data,) = cursor.fetchone()

but the problem is that now data returns a string while i need it to be a list of dictionaries as earlier. Please suggest some way through which i can get the value of my field from database as list of dictionaries

  • How did you create the string in the first place? Is it always going to be in JSON format? – Chris Jan 11 '20 at 13:56
  • Does this answer your question? [What's the best way to parse a JSON response from the requests library?](https://stackoverflow.com/questions/16877422/whats-the-best-way-to-parse-a-json-response-from-the-requests-library) (The source of the JSON—a database or HTTP—doesn't really matter.) – Chris Jan 11 '20 at 13:57

1 Answers1

0

You can use the json module as suggested in the comments, for example something like this should work:

import json

long_text = '[{"A":"apple"}, {"B":"ball"} , {"c":"cat"}]'
list_of_dicts = json.loads(long_text)
print(list_of_dicts)

>>> [{'A': 'apple'}, {'B': 'ball'}, {'c': 'cat'}]
marcos
  • 4,099
  • 1
  • 6
  • 18