Writing a list
to a JSON
file writes one element at per line.
How can I write a list to one line, maintaining its dtype
?
separators=(','...
is enforcing this (needed for separating key-value
pairs). How can I make an exception clause for lists?
import json
my_list = [1, 2, 3]
data = {
'my_list': my_list
}
with open('test.json', 'w') as json:
json.dump(data, json, indent=4, separators=(',', ': '))
test.json
data = {
'my_list': [
1,
2,
3
],
'another key': "val"
}
Desired output:
data = {
'my_list': [1, 2, 3],
'another key': "val"
}
For what I am looking for, YAML
is the best alternative. It allows you to write what would be Python
lists
on one line.