Here is the solution for first level nested conversion.
import json
input_list = [{'item1':"value",'item2':[{'tinyitem21':'tinyvalue21','tinyitem22':'tinyvalue22'}]},{'item3':[{'tinyitem31':'tinyvalue31','tinyitem32':'tinyvalue32'}],'item4':'value4'}]
for index, j in enumerate(range(len(input_list))):
for key, value in input_list[index].items():
if isinstance(value, list) and len(value) == 1: # Checking for single dictionary as multiple values of dict cannot considered as json
input_list[index][key] = value[0]
print(json.dumps(input_list, indent=3))
Output:
[
{
"item1": "value",
"item2": {
"tinyitem21": "tinyvalue21",
"tinyitem22": "tinyvalue22"
}
},
{
"item3": {
"tinyitem31": "tinyvalue31",
"tinyitem32": "tinyvalue32"
},
"item4": "value4"
}
]
And let say if the value at item2
at index 0 has more than one dict then it should be considered as string value as shown in below output
import json
input_list = [{'item1':"value",'item2':[{'tinyitem21':'tinyvalue21','tinyitem22':'tinyvalue22'},{'tinyitem23':'tinyvalue21','tinyitem24':'tinyvalue22'}]},{'item3':[{'tinyitem31':'tinyvalue31','tinyitem32':'tinyvalue32'}],'item4':'value4'}]
for index, j in enumerate(range(len(input_list))):
for key, value in input_list[index].items():
if isinstance(value, list): # without checking len of list
input_list[index][key] = ','.join(map(str, value)) # string value be assigned instead of dictionary
print(json.dumps(input_list, indent=3))
Output will be string instead of dict but if you notice item3
being single dict of list but still being assinged as str.
[
{
"item1": "value",
"item2": "{'tinyitem21': 'tinyvalue21', 'tinyitem22': 'tinyvalue22'},{'tinyitem23': 'tinyvalue21', 'tinyitem24': 'tinyvalue22'}"
},
{
"item3": "{'tinyitem31': 'tinyvalue31', 'tinyitem32': 'tinyvalue32'}",
"item4": "value4"
}
]
To handle both list with one/many dict with more readability.
for index, j in enumerate(range(len(input_list))):
for key, value in input_list[index].items():
if isinstance(value, list) and len(value) == 1: # Checking for single dictionary as multiple values of dict cannot considered as json
input_list[index][key] = value[0]
if isinstance(value, list) and len(value) > 1: # for list of dict with more than one
input_list[index][key] = ','.join(map(str, value)) # string value be assigned instead of dictionary
if you want to use comprehensive way mentioned by CDJB you need to add one more condition to it because if in case of list with size more than 1 it will silently ignore second index.
[{k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in d.items()} for d in input_list]
Output:
[
{
"item1": "value",
"item2": "{'tinyitem21': 'tinyvalue21', 'tinyitem22': 'tinyvalue22'},{'tinyitem23': 'tinyvalue21', 'tinyitem24': 'tinyvalue22'}"
},
{
"item3": {
"tinyitem31": "tinyvalue31",
"tinyitem32": "tinyvalue32"
},
"item4": "value4"
}
]