【问题标题】:converting csv file into json format in python在python中将csv文件转换为json格式
【发布时间】:2019-08-15 08:36:34
【问题描述】:

我已经编写了一个代码来转换我的 csvfile 是 '|'分隔文件以获取特定的 json 格式。

CSV 文件格式:

comment|address|city|country
crowded|others|others|US
pretty good|others|others|US .... 

我也尝试过其他代码,因为我是 python 新手,我被困在两者之间。如果有人帮助我纠正我正在做的错误,那将会很有帮助。

import csv
import json
from collections import OrderedDict

csv_file = 'test.csv'
json_file = csv_file + '.json'


def main(input_file):
    csv_rows = []
    with open(input_file, 'r') as csvfile:
        reader = csv.DictReader(csvfile)
        title = reader.fieldnames
        for row in reader:
            entry = OrderedDict()
            for field in title:
                entry[field] = row[field]
            csv_rows.append(entry)

    with open(json_file, 'w') as f:
        json.dump(csv_rows, f, sort_keys=True, indent=4, ensure_ascii=False)
        f.write('\n')


if __name__ == "__main__":
    main(csv_file)

我想要下面的json格式

{ 
 "reviewer": {
    "city": "",
    "country": ""   
    "address": "Orlando, Florida"
  },

但我得到这样的输出:

[
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"Crowded"|"Others"|"Others"|
  },
  {
    "COMMENT|\"ADDRESS\"|\"CITY\"|"COUNTRY":"pretty good"|"Others"|"Others"|
  },

【问题讨论】:

  • 如何以嵌套的 json 格式获得相同的输出?我正在使用这种格式。[ { "ADDRESS": "Others", "CITY": "Others", "COUNTRY": "Others" } ] 但我想要嵌套 json 格式的输出,例如 { "reviewer": {“城市”:“”,“国家”:“”“地址”:“佛罗里达州奥兰多”}}

标签: python json python-2.7 csv


【解决方案1】:

您缺少分隔符参数。而不是:

reader = csv.DictReader(csvfile)

用途:

reader = csv.DictReader(csvfile, delimiter='|')

【讨论】:

  • 谢谢。我现在得到了 json 结构。
  • 如何检查我编写的上述程序中的特定字段值。我有 2 个字段“推荐”和“评分”。根据推荐,我需要为评分设置值,例如如果推荐为 1,则评分为 1,反之亦然
  • 这是其他问题的链接。 stackoverflow.com/questions/55333086/…
猜你喜欢
  • 2018-03-06
  • 2018-08-15
  • 1970-01-01
  • 2020-11-11
  • 2022-01-04
  • 2015-01-13
  • 1970-01-01
  • 1970-01-01
  • 2016-11-06
相关资源
最近更新 更多