0

I have the following code which prints the object as 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)

I get:

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

I want to print the same data as JSON in order to get:

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

From previous topics I learn that we can use json.dumps but I'm not sure if it helps in this case. What is the proper way to achieve it?

1

1 Answer 1

0

You could simply do:

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)

to get a json like file.

You can also avoid appending and do:

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

You can use json.dump to dump l in a file

import json
with open('data.json', 'w') as outfile:
    json.dump(l, outfile)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.