Skip to content Skip to sidebar Skip to footer

Tuples Conversion Into Json With Python

I would like some help converting a tuple in format [(X, Y, Z),(..) of type (string, string, int)] to a JSON file in the format: { 'name': 'X', 'children': [{ '

Solution 1:

Assuming you want a list of dicts as the output of the json with each dict be the form in your question:

The following one liner will put it into the data structure your looking for with each tuple generating it's own complete structure:

[{'name':i[0], 'children': [{'name': i[1], 'value': i[2]}]}  for i in tuples]

But I suspect you want the outer name to be unique with inner children being built from multiple tuples, such that there is only one such structure generated with 'name' == X.

To do it in a memory efficient manner start by sorting your tuples by X:

# should work as long as you aren't doing any fancy sorting
stuples = sorted(tuples) 

name = None
dat = Nonefor t in stuples:
    if name != t[0]:
        if dat isnotNone:
            writeDat(json.dumps(dat))
        name = t[0]
        dat = {'name': t[0], 'children': [{'name': t[1], 'value': t[2]}]}
    else:
        dat['children'].append({'name': t1, 'value': t[2]})

I assume you have a function to write one of these out such as writeDat() that takes the json so you aren't storing them all in ram.

Solution 2:

import json 
list_of_tuples = [('jack', 'jill', 5), ('baba','black', 6)]
result = list()
for each_tuple in list_of_tuples:
    temp = dict()
    temp['name'] = each_tuple[0]
    temp['children'] = [{'name': each_tuple[1],'value':each_tuple[2]}]
    result.append(temp)

json.dumps(result)

Updated.

Post a Comment for "Tuples Conversion Into Json With Python"