Reputation: 525
I'm manually constructing a JSON so I want the last element to not have a ,
seperator before the ]
.
This my code and the documentation says len() works for tuples but I can't get it to work.
The data
is a tuple constructed from a SQLite.fetchall() and it has been validated.
for row in data:
f.write("{\n")
f.write(f"'PUT':'{row[1]}'\n")
if row == len(data): # I also tried len(data)-1 as suggested by posts
f.write("}\n")
else:
f.write("},\n")
This code constructs the JSON but all elements including the last have the ,
separator.
What is the best pythonic way to do this?
Upvotes: -1
Views: 104
Reputation: 13106
Use a str.join
to help you format the records, that will get all except the last one, and you can concatenate on the \n
to the last record:
# concatenate the last `\n` onto the end after joining
records = ',\n'.join(
"{\n'PUT':'{value}'\n}".format(value=row[1])
for row in data
) + '\n'
with open(file) as fh:
fh.write(records)
Since it looks like you are trying to roll your own in terms of json encoding, don't. You can make this easier by doing:
import json
records = ',\n'.join(
(json.dumps({"PUT": row[1]}, indent=0), for row in data)
) + '\n'
Where the indent=0
kwarg will insert the newlines you want:
# compare the two
json.dumps({"some": "value"}, indent=0)
'{\n"some": "value"\n}'
json.dumps({"some": "value"})
'{"some": "value"}'
Upvotes: 1
Reputation: 525
Solved it
if row == data[len(data)-1]:
f.write("}\n")
else:
f.write("},\n")
Upvotes: 0