It is currently not producing the JSON I want there are many issues that I have listed but I am wondering what would make it produce what I want I know that there is probably a simple way to this but I cannot figure it out.
I have this function that takes in a list of lists
def convert_to_json(data):
result = {}
def set_nested_value(d, keys, value):
if len(keys) == 1:
if isinstance(value, list):
# Create a list of dictionaries
lists = [v for v in value if isinstance(v, list)]
max_len = max((len(v) for v in lists), default=0)
for i in range(max_len):
obj = {}
for idx, v in enumerate(value):
if isinstance(v, list) and i < len(v):
obj[keys[0]] = v[i]
elif idx == 0:
obj[keys[0]] = None
if keys[0] not in d:
d[keys[0]] = []
d[keys[0]].append(obj)
else:
d[keys[0]] = value
else:
if keys[0] not in d:
d[keys[0]] = {}
set_nested_value(d[keys[0]], keys[1:], value)
for key, value in data:
keys = key.split('.')
set_nested_value(result, keys, value)
# Remove None values from lists in the final output
def clean_none_values(d):
if isinstance(d, list):
return [clean_none_values(item) for item in d if item is not None]
elif isinstance(d, dict):
return {k: clean_none_values(v) for k, v in d.items()}
else:
return d
return json.dumps(clean_none_values(result), indent=4)
this is a sample of what the data produces
{
"Children": {},
"Spouse": {
"AddressLine1": "450 Main",
"AddressLine2": "Apt 1",
}
"TrueFalse": "true",
"DateVariable": "16/7/2024"
}
to get this data the list inserted is this
[
["Children.AddressLine1",["child1address","child2address",null]],
["Children.AddressLine2",["child1address2","child2address2",null]],
["Spouse.AddressLine1","450 Main"],
["Spouse.AddressLine2","Apt 1"],
['TrueFalse', 'true'],
['DateVariable', '16/7/2024']]
the result I want is
{
"Children": [
{
"AddressLine1": "child1address",
"AddressLine2": "child1address2"
},
{
"AddressLine1": "child2address",
"AddressLine2": "child2address2"
}
],
"Spouse": {
"AddressLine1": "450 Main",
"AddressLine2": "Apt 1",
}
"TrueFalse": true,
"DateVariable": "2024-07-16"
}
how would I go about doing this is there a simple way that I am overlooking.
Artificial_Float is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2