change single quotes to double quotes in list of dictionaries

Viewed 421

input=

list1=[{'Name':'Jack','email':'xyz@foo.com'},
          {'Name':'Sam','email':'sam@xyz.com'},
          {'Name':'Dan','email':'dan@xyz.com'}]

Required output =

list1=[{"Name":"Jac","email":"xyz@foo.com"},
          {"Name":"Sam","email":"sam@xyz.com"},
          {"Name":"Dan","email":"dan@xyz.com"}]

How to get this as output? I've tried

list2=[]

for items in response:
    list2.append(json.dumps(items))

output I'm getting is

['{'Name':'Jack','email':'xyz@foo.com'}',
          '{'Name':'Sam','email':'sam@xyz.com'}',
          '{'Name':'Dan','email':'dan@xyz.com'}']
2 Answers

Please use json.dumps like this:

import json

list1=[{'Name':'Jack','email':'xyz@foo.com'},
          {'Name':'Sam','email':'sam@xyz.com'},
          {'Name':'Dan','email':'dan@xyz.com'}]

print(list1)

list2 = json.dumps(list1)
print(list2)

#[{'Name': 'Jack', 'email': 'xyz@foo.com'}, {'Name': 'Sam', 'email': 'sam@xyz.com'}, {'Name': 'Dan', 'email': 'dan@xyz.com'}]
#[{"Name": "Jack", "email": "xyz@foo.com"}, {"Name": "Sam", "email": "sam@xyz.com"}, {"Name": "Dan", "email": "dan@xyz.com"}]

Generally, you want to do json.dumps() on the whole data structure, not on individual pieces.

It's not clear from your question what form the input is; is it a data structure in a file, or in memory?

If it's in a file, the first step will be reading it, so it's in memory, and so each part has the right form.

Once that's done, you can do json.dumps() on the whole list.

Related