I am working with Python and some json data. I am looping through my data (which are all dictionaries) and when I print the loop values to my console, I get 1 dictionary per line.
However, when I do the same line of code with json.dumps() to convert my object into a string to be able to be output, I get multiple lines within the dictionary versus wanting the new line outside the dictionary.
How do you add new lines after each dictionary value when looping?
Code example:
def test(values, filename):
with open(filename, 'w') as f:
for value in values:
print(json.dumps(value, sort_keys=True)) # gives me each dictionary in a new line
f.write(json.dumps(value, sort_keys=True, indent=0) #gives me a new line for each key/value pair instead of after each dictionary.
Output in the console:
{"first_name": "John", "last_name": "Smith", "food": "corn"}
{"first_name": "Jane", "last_name": "Doe", "food": "soup"}
Output in my output file:
{"first_name": "John", "last_name": "Smith", "food": "corn"}{"first_name": "Jane", "last_name": "Doe", "food": "soup"}
What code am I missing to get a new line for each dictionary value so that my output file looks the same as my console?
You can newline after each
f.write(json.dumps(value, sort_keys=True, indent=0))
like this - f.write('\n')