'Create nested json from list of dicts and list of strings
I have 3 list of dicts and a list of strings that I need to convert into json format. TBH, I am not sure where to begin but if anyone can point me in the right direction, that will be super helpful
lst_strings = ['one', 'two']
d1 = [{'a':1, 'b':2, 'c':3}]
d2 = [{'d':4, 'e':5, 'f':6}, {'d':7, 'e':8, 'f':9}]
d3 = [{'z': '0'}, {'g': 'false'}]
The json output I am looking for is formatted like this:
{
"one": [{
"a": "1",
"b": "2",
"c": "3",
"two": [{
"d": "4",
"e": "5",
"f": "6"
}, {
"d": "7",
"e": "8",
"f": "9"
}],
"z": "0"
}],
"g": false
}
What will be the best and most efficient way to achieve this result. I know I should post what I have done so far but honestly, my brain is dysfunctional at the moment.
Solution 1:[1]
Try this:
import json
lst_strings = ['one', 'two', 'three']
d1 = [{'a':1, 'b':2, 'c':3}]
d2 = [{'d':4, 'e':5, 'f':6}, {'d':7, 'e':8, 'f':9}]
d3 = [{'z': '0'}, {'g': 'false'}]
d = {}
for i,s in enumerate(lst_strings):
d[s] = eval(f'd{i+1}')
j = json.dumps(d)
print(j)
Output:
{"one": [{"a": 1, "b": 2, "c": 3}], "two": [{"d": 4, "e": 5, "f": 6}, {"d": 7, "e": 8, "f": 9}], "three": [{"z": "0"}, {"g": "false"}]}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | C. Pappy |
