繁体   English   中英

将dict的字符串列表从csv转换为python中的JSON对象

[英]Convert string list of dict from csv into JSON object in python

我有一个CSV,其中一列值在字典列表中,如下所示

[{'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原始list of dict类型。

我如何才能真正做到这一点。

解决方案:

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

转换为json文件:

>>> import json
>>> json.dump(obj,open(path + '/txt.json','w+'))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM