1

I 'm a Python beginner, I have a list that needs to be converted to json format. I hope to get some help.

raw data:

result = [('A', 'a1', '1'),
          ('A', 'a2', '2'),
          ('B', 'b1', '1'),
          ('B', 'b2', '2')]

The result I want:

[{'type':'A',
  'data':[{'name':'a1','url':'1'},
          {'name':'a2','url':'2'}]
 },
 {'type': 'B',
  'data': [{'name':'b1', 'url': '1'},
           {'name':'b2','url':'2'}]
 }]
dev101
  • 1,359
  • 2
  • 18
  • 32
张嘉斌
  • 13
  • 2
  • Possible duplicate of [Python Tuple to JSON output](https://stackoverflow.com/questions/5087903/python-tuple-to-json-output) – deedub Feb 21 '19 at 15:36

1 Answers1

1

('A', 'a1', 1) is an example of a tuple, which are iterable.

result = [('A', 'a1', '1'),
          ('A', 'a2', '2'),
          ('B', 'b1', '1'),
          ('B', 'b2', '2')]
type_list = []
for tup in result:
    if len(type_list) == 0:
        type_list.append({'type': tup[0], 'data': [{ 'name': tup[1], 'url': tup[2] }]})
    else:
        for type_obj in type_list:
            found = False
            if type_obj['type'] == tup[0]:
                type_obj['data'].append({ 'name': tup[1], 'url': tup[2] })
                found = True
                break 
        if not found: 
            type_list.append({'type': tup[0], 'data': [{ 'name': tup[1], 'url': tup[2] }]})
print(type_list)

which prints:

[{'type': 'A', 'data': [{'name': 'a1', 'url': '1'}, {'name': 'a2', 'url': '2'}]}, {'type': 'B', 'data': [{'name': 'b1', 'url': '1'}, {'name': 'b2', 'url': '2'}]}]
deedub
  • 176
  • 7