具有特定格式的CSV到JSON

时间:2017-10-09 20:57:13

标签: python json csv dictionary api-design

我有csv文件包含此数据并使用python我想以json格式转换。

我想以这种格式转换Json Format.Can你告诉我应该使用哪个库或者对sudo代码有任何建议。 我可以转换为具有键值对的标准json,但我不知道如何在Json格式下转换。

"T-shirt","Long-tshirt",18
"T-shirt","short-tshirt"19
"T-shirt","half-tshirt",20
"top","very-nice",45
"top","not-nice",56



{
"T-shirts":[
  {
  "name":"Long-tshirt",
  "size":"18"
  },
  {
  "name":"short-tshirt",
  "size":"19"
  },
  {
  "name":"half-tshirt",
  "size":"20"
  },
  ],
"top":[
  {
  "name":"very-nice"
  "size":45
  },
  {
  "name":"not-nice"
  "size":45
  },
  ]
}




2 个答案:

答案 0 :(得分:1)

在此代码中,我将您的CSV放入test.csv文件中:(作为抬头,提供的代码在19之前缺少逗号)。

"T-shirt","Long-tshirt",18
"T-shirt","short-tshirt",19
"T-shirt","half-tshirt",20
"top","very-nice",45
"top","not-nice",56

然后,使用内置的csvjson模块,您可以迭代每一行并将它们添加到字典中。我使用defaultdict来节省时间,并将该数据写入json文件。

import csv, json
from collections import defaultdict

my_data = defaultdict(list)

with open("test.csv") as csv_file:
    reader = csv.reader(csv_file)
    for row in reader:
        if row: # To ignore blank lines
            my_data[row[0]].append({"name": row[1], "size": row[2]})


with open("out.json", "w") as out_file:
    json.dump(my_data, out_file, indent=2)

生成的文件:

{
  "T-shirt": [
    {
      "name": "Long-tshirt",
      "size": "18"
    },
    {
      "name": "short-tshirt",
      "size": "19"
    },
    {
      "name": "half-tshirt",
      "size": "20"
    }
  ],
  "top": [
    {
      "name": "very-nice",
      "size": "45"
    },
    {
      "name": "not-nice",
      "size": "56"
    }
  ]
}

答案 1 :(得分:-3)

import json

json_string = json.dumps(your_dict)

您现在有一个字符串,其中包含原始字典中的json格式化日期 - 这是您想要的吗?