【问题标题】:Convert string list of dict from csv into JSON object in python将 dict 的字符串列表从 csv 转换为 python 中的 JSON 对象
【发布时间】:2018-08-30 12:56:54
【问题描述】:

我有一个 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)

【问题讨论】:

  • 请显示数据文件的内容,您用来读取该数据的代码。这将有很大帮助。

标签: python json csv csv-import


【解决方案1】:

转成json文件:

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

【讨论】:

  • 这更好,但它仍然只回答了问题的第二部分;)
  • 第一部分在前面的回答中用 ast 模块回答。我不想重复它;)@bruno desthuilliers
【解决方案2】:

您可以使用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的那个确实是一个更好的主意。
  • @Gabriel。我没有提到eval,因为它有时会很危险link
猜你喜欢
  • 2016-06-24
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-27
  • 2018-01-08
  • 2020-05-16
  • 2021-04-14
  • 2015-05-17
相关资源
最近更新 更多