Reputation: 31
import json
data = ['A + G', 'B + F', 'C + E', 'D + D']
print(json.dumps(data, indent=0))
The above code displays the output:
[
"A + G",
"B + F",
"C + E",
"D + D"
]
But I want it to be:
["A + G",
"B + F",
"C + E",
"D + D"]
I have tried changing the indent of the Json, but that doesn't work. Where am I going wrong here?
Upvotes: 0
Views: 130
Reputation: 469
print('['+json.dumps(data, indent=1)[3:-2]+']')
is really ugly, but works
Upvotes: 1
Reputation: 69
Quick and dirty:
import json
def cut_ends(string):
string = string.replace('\n]',']')
string = string.replace('[\n','[')
return string
data = ['A + G', 'B + F', 'C + E', 'D + D']
print(cut_ends(json.dumps(data, indent=0)))
Upvotes: 0
Reputation: 66
Another shorter, but hackier way: (if you know you'll always have '[\n' and '\n]' at the start and end) strip those chars and just put '[' and ']'
import json
data = ['A + G', 'B + F', 'C + E', 'D + D']
raw = json.dumps(data, indent=0)
new = raw[2:-2]
print('['+new+']')
Upvotes: 0
Reputation: 15130
If you are just using json
for the print output, you can skip it and get the output you want with something like:
data = ['A + G', 'B + F', 'C + E', 'D + D']
for i, d in enumerate(data):
if (i == 0):
print('["{}"'.format(d))
elif (i == len(data) - 1):
print(' "{}"]'.format(d))
else:
print(' "{}"'.format(d))
# OUTPUT
# ["A + G"
# "B + F"
# "C + E"
# "D + D"]
Upvotes: 1