以与CSV相同的格式将数据转换为JSON

时间:2019-11-25 18:01:19

标签: python json csv

我有以下代码将对象打印为CSV:

title = ['Username', 'Name', 'Job']
for x in title:
    print(x, end =",")

for d in data:
    line = d.get_username() + "," + d.get_name() + "," + d.get_role()
    print(line)

我得到:

Username,Name,Job
rob,robert,developer
danny21,danny,developer

我想打印与JSON相同的数据以获取:

[ 
   { 
      "Username":"rob",
      "Name":"robert",
      "Job":"developer"
   },
   { 
      "Username":"danny21",
      "Name":"danny",
      "Job":"developer"
   }
]       

从先前的主题中,我了解到可以使用json.dumps,但不确定在这种情况下是否有帮助。 实现它的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

您可以简单地做到:

l = []
for d in data:
    user_dictionary = {}
    user_dictionary[title[0]] = d.get_username()
    user_dictionary[title[1]] = d.get_name()
    user_dictionary[title[2]] = d.get_role()
    l.append(user_dictionary)

获取类似json的文件。

您还可以避免附加并执行操作:

def get_user_data(user):
    user_dictionary = {}
    user_dictionary[title[0]] = d.get_username()
    user_dictionary[title[1]] = d.get_name()
    user_dictionary[title[2]] = d.get_role()
    return user_dictionary

l = list(map(get_user_data, data))

您可以使用json.dump将l转储到文件中

import json
with open('data.json', 'w') as outfile:
    json.dump(l, outfile)