У меня есть csv, где значения одного столбца находятся в списке dict, как показано ниже
[{'10': 'i ve been with what is now comcast since 2001 the company has really grown and improved and delivers a great service along with great customer service ', 'aspects':['service']},
{'20': 'good service but lack of options to allow it be more affordable allowing individual channel choices would be great ', 'aspects':['lack', 'service']},
{'30': 'it a good service but very expensive', 'aspects':['service']}, {'40': 'good service', 'aspects':['service']},
{'50': 'good service but over priced ', 'aspects':['service']}]
Теперь, потому что, когда я читаю это с CSV, это string, я не могу преобразовать его в исходный тип list of dict, а затем в json.
Как я могу этого добиться.
Решение :
data = output[output.aspects == aspect]['column1'].tolist()
listData=ast.literal_eval(data[0])
return json.dumps(listData)






Вы можете использовать модуль ast
Бывший:
import ast
s = """[{'10': 'i ve been with what is now comcast since 2001 the company has really grown and improved and delivers a great service along with great customer service ', 'aspects':['service']},
{'20': 'good service but lack of options to allow it be more affordable allowing individual channel choices would be great ', 'aspects':['lack', 'service']},
{'30': 'it a good service but very expensive', 'aspects':['service']}, {'40': 'good service', 'aspects':['service']},
{'50': 'good service but over priced ', 'aspects':['service']}]"""
print(ast.literal_eval(s))
Выход:
[{'10': 'i ve been with what is now comcast since 2001 the company has really grown and improved and delivers a great service along with great customer service ', 'aspects': ['service']}, {'aspects': ['lack', 'service'], '20': 'good service but lack of options to allow it be more affordable allowing individual channel choices would be great '}, {'30': 'it a good service but very expensive', 'aspects': ['service']}, {'aspects': ['service'], '40': 'good service'}, {'aspects': ['service'], '50': 'good service but over priced '}]
Я собирался предложить встроенный eval, но ast действительно лучше.
@ Габриэль. Я не упомянул eval, потому что иногда это может быть опасно ссылка на сайт
Чтобы преобразовать в файл json:
>>> import json
>>> json.dump(obj,open(path + '/txt.json','w+'))
Это лучше, но это все еще отвечает только на вторую часть вопроса;)
На первую часть ответ дан в предыдущем ответе с помощью модуля ast. Не хочу повторяться;) @bruno desthuilliers
Пожалуйста, покажите содержимое файла данных, код, который вы используете для чтения этих данных. Это очень поможет.