简体   繁体   中英

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

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

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 .

Solution :

  data = output[output.aspects == aspect]['column1'].tolist()
  listData=ast.literal_eval(data[0])

  return json.dumps(listData)

You can use the ast module

Ex:

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))

Output:

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

To convert to json file:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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