I want to convert a python list into json, here's the input
obj=([{'value1': 'a', 'value2': None, 'value3': 'abc', 'value4': 'xyz', 'value5': 'tes', 'value6': None, 'value7': None, 'value8': 'a'}],
[{'value1': 'b', 'value2': None, 'value3': 'abc', 'value4': 'uyt', 'value5': 'tuy', 'value6': None, 'value7': None, 'value8': 'b'}])
Desired Output:
{ "file": [
{
"value1": "a",
"value2": None,
"value3": "abc",
"value4": "uyt",
"value5": "tuy",
"value6": None,
"value7": None,
"value8": "a",
},
{
"value1": "b",
"value2": None,
"value3": "abc",
"value4": "xyz",
"value5": "tes",
"value6": None,
"value7": None,
"value8": "b",
}
]
}
PS: I followed some existing issues on StackOverflow, but it's not working for me. Thank you. :)
This should work for any number of lists:
import json
obj = (
[{
'value1': 'a', 'value2': None, 'value3': 'abc', 'value4': 'xyz', 'value5': 'tes', 'value6': None, 'value7': None, 'value8': 'a'
}],
[{
'value1': 'b', 'value2': None, 'value3': 'abc', 'value4': 'uyt', 'value5': 'tuy', 'value6': None, 'value7': None, 'value8': 'b'
}]
)
result = {'file': []}
for l in obj:
result['file'].append(l[0])
result_json = json.dumps(result, indent=2)
print(result_json)
Output:
{
"file": [
{
"value1": "a",
"value2": null,
"value3": "abc",
"value4": "xyz",
"value5": "tes",
"value6": null,
"value7": null,
"value8": "a"
},
{
"value1": "b",
"value2": null,
"value3": "abc",
"value4": "uyt",
"value5": "tuy",
"value6": null,
"value7": null,
"value8": "b"
}
]
}