Why json.dump() and .load() are really needed?
Python dumps "\n" instead of a newline in a json file - Stack Overflow
python 3.x - why json.dumps add \n in the output,how should I remove it while saving it in a file? - Stack Overflow
Python json.dumps() outputs all my data into one line but I want to have a new line for each entry - Stack Overflow
Hi, hope everyone is well.
Just nearing the basics end of PCC book, I'm at saving user's data now. What exactly is the reason, when storing simple data, to use json.dump() or load(), instead of just saving and then reading it from simple text file?
I just can't place it in my head why do I really need it and it always makes it more difficult for me to learn if that's the case.
Thank you all in advance.
You are using pretty print, if you want to avoid new lines do not use indent flag.
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
print(json.dumps(data))
{"people": [{"name": "Scott", "website": "stackabuse.com", "from": "Nebraska"}]}
Your version just use nice formatting:
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
print(json.dumps(data, indent=4))
{
"people": [
{
"name": "Scott",
"website": "stackabuse.com",
"from": "Nebraska"
}
]
}
In addition - new lines have no matter for json. Below two examples works same:
import json
data = {'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
with open('/tmp/file1', 'w') as f:
json.dump(data, f, indent=4)
with open('/tmp/file2', 'w') as f:
json.dump(data, f)
with open('/tmp/file1') as f:
print(json.load(f))
with open('/tmp/file2') as f:
print(json.load(f))
{'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
{'people': [{'name': 'Scott', 'website': 'stackabuse.com', 'from': 'Nebraska'}]}
Because you ask it to, by providing indent. Just doing json.dumps(data) will not insert any newlines.
If you want to produce valid JSON file you need to write all values at once, not one value at a time (which will produce ndjson or JSON lines)
So, for a valid JSON
values = [{"first_name": "John", "last_name": "Smith", "food": "corn"},
{"first_name": "Jane", "last_name": "Doe", "food": "soup"}]
import json
with open('some_file.json', 'w') as f:
json.dump(values, f, indent=4)
some_file.json
[
{
"first_name": "John",
"last_name": "Smith",
"food": "corn"
},
{
"first_name": "Jane",
"last_name": "Doe",
"food": "soup"
}
]
if you really need ndjson - you can use ndjson package (need install via pip from PyPi).
import ndjson
with open('some_file2.ndjson', 'w') as f:
ndjson.dump(values, f)
some_file2.ndjson
{"first_name": "John", "last_name": "Smith", "food": "corn"}
{"first_name": "Jane", "last_name": "Doe", "food": "soup"}
Alternative to ndjson package is jsonlines package
You can newline after each
f.write(json.dumps(value, sort_keys=True, indent=0))
like this - f.write('\n')