Python Forum

Full Version: convert unlabeled list of tuples to json (string)
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Say i have a list of unlabeled tuples which i want to convert to JSON
Where each tuple is an object (of the same type) which represents a user
the first value of the tuple represents a 'username' and second a 'role'
Sample Input:
[('Andy', '001'), ('Off0', '010'), ('Pla0', '100'), ('Pla1', '100'), ('Pla2', '100'), ('Pla3', '100')]
Output:
Output:
[ { "username": "Andy", "role": "001" }, { "username": "Off0", "role": "010" }, { "username": "Pla0", "role": "100" }, { "username": "Pla1", "role": "100" }, { "username": "Pla2", "role": "100" }, { "username": "Pla3", "role": "100" }, ]
Note: i do not care about the white spaces

i can convert one tuple with:
json.dumps({'username':list[0][0], 'role':list[0][1]})
but i do not understand to conbine all the tuples of the list together

Thanks!

P.S. i am python newbie, but i am familiar with the basic concepts (like syntax)
import json
users = [('Andy', '001'), ('Off0', '010'), ('Pla0', '100'), ('Pla1', '100'), ('Pla2', '100'), ('Pla3', '100')]
keys = ['username', 'role']

data = [dict(zip(keys, user)) for user in users]
json_data = json.dumps(data, indent=4)
print(json_data)
(Apr-26-2021, 06:42 PM)buran Wrote: [ -> ]
import json
users = [('Andy', '001'), ('Off0', '010'), ('Pla0', '100'), ('Pla1', '100'), ('Pla2', '100'), ('Pla3', '100')]
keys = ['username', 'role']

data = [dict(zip(keys, user)) for user in users]
json_data = json.dumps(data, indent=4)
print(json_data)



Thanks man!

Explaining what you did for anyone in the future who has this problem
data = [dict(zip(keys, user)) for user in users]
converts the (unlabeled) tuple to a dictionary (effectivly a named tuple)
and then
json_data = json.dumps(data, indent=4)
simply encode it
(Apr-26-2021, 06:59 PM)masterAndreas Wrote: [ -> ]dictionary (effectivly a named tuple)
dict is not namedtuple! These are two very different container types

If you want to use namedtuple

import json
from collections import namedtuple
users = [('Andy', '001'), ('Off0', '010'), ('Pla0', '100'), ('Pla1', '100'), ('Pla2', '100'), ('Pla3', '100')]
User = namedtuple('User', 'username role')
print(User('Andy', '001'))
data = [User(*item)._asdict() for item in users]
json_data = json.dumps(data, indent=4)
print(json_data)
In my opinion simply using a dict is better.
Quote:dictionary (effectively a named tuple)

would it be more accurate if I rephrased as
Quote:dictionary (effectively for our purposes, a pseudo named-tuple)