Tuples conversion into JSON with python [closed]

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 = None
for t in stuples:
    if name != t[0]:
        if dat is not None:
            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.

Leave a Comment