将dict的字符串列表从csv转换为python中的JSON对象 [英] Convert string list of dict from csv into JSON object in python

查看:108
本文介绍了将dict的字符串列表从csv转换为python中的JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv,其中一列值位于下面的字典列表中

I have a csv where for one column values are in list of dict like below

[{'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的原始类型的字典然后是 json

Now because when I am reading this from CSV its a string I am not able to convert it to original type of list of dict and then json .

我实际上是如何实现的。

How I can actually achieve this .

解决方案:

  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 '}]

这篇关于将dict的字符串列表从csv转换为python中的JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆