Skip to content Skip to sidebar Skip to footer

Python List Of (node_id, Parent_node_id) To Json

I have a list with the following structure: [(node_id, parent_node_id),..(node_id, parent_node_id)] example: data = [(1, None), (4, 1), (15, 1),

Solution 1:

Use json.dumps or json.dump:

>>>data = [...    (1, None),...    (4, 1),...    (15, 1),...    (6, 1),...    (2, 1),...    (7, 1),...    (12, 7),...    (13, 7),...    (17, 13),...    (18, 17),...    (14, 7),...    (8, 1),...    (9, 1),...    (10, 1),...    (11, 1),...    (19, 1),...    (16, None)...]>>>import json>>>json.dumps(data)
'[[1, null], [4, 1], [15, 1], [6, 1], [2, 1], [7, 1], [12, 7], [13, 7], [17, 13], [18, 17], [14, 7], [8, 1], [9, 1], [10, 1], [11, 1], [19, 1], [16, null]]'
>>>

Solution 2:

you really need to inspect your system requirements. A list of tuples does not lend itself well to what you are trying to accomplish. However, if you are locked by some external requirements that you don't control, here is a sample solution.

@falsetru is correct, you will need to use JSON.dumps, but only AFTER you convert your input data to your desired output format

import json
data = [(1, None),
            (4, 1),
            (15, 1),
            (6, 1),
            (2, 1),
            (7, 1),
                (12, 7),
                (13, 7),
                    (17, 13),
                        (18, 17),
                (14, 7),
            (8, 1),
            (9, 1),
            (10, 1),
            (11, 1),
            (19, 1),
        (16, None)]

defconvert(input):
    loading_struct = {} #load your tuples into a dict object (because I like dict)
    alignment_struct = {} #structure to hold the output
    seen_embedded_keys = {} #keep track of items we have seen before to remove themfor line ininput: #iterating your input of a list of tuples
        loading_struct[line[0]] = line[1] #unloading them unto a dictionary
        alignment_struct[line[0]] = {} #creating a blank result dictionary with your proposed outputfor node_id, parent_node_id in loading_struct.items(): #iterating the loading structif parent_node_id: #if it doesnt have a parent, we dont need to do anything
            alignment_struct[parent_node_id][node_id] = alignment_struct[node_id]
            seen_embedded_keys[node_id] = Truefor node_id in seen_embedded_keys: #cleanup time remove the keys that are embedded somewhere elsedel alignment_struct[node_id]
    return alignment_struct

output = json.dumps(convert(data)).replace('{}', '""') #your requirement to have nodes with no children to have values of ''print output

the output of the above script will print

{"1":{"2":"","4":"","6":"","7":{"12":"","13":{"17":{"18":""}},"14":""},"8":"","9":"","10":"","11":"","15":"","19":""},"16":""}

Again, please double check your requirements to optimize those first.

Post a Comment for "Python List Of (node_id, Parent_node_id) To Json"