Home > Blockchain >  Removing last comma in json file
Removing last comma in json file

Time:10-24

I am creating a json file like this

[
{"_index": "java", "_id": "15194804", "rating": 0},
{"_index": "java", "_id": "18264178", "rating": 0},
{"_index": "java", "_id": "16225177", "rating": 1},
{"_index": "java", "_id": "16445238", "rating": 0},
{"_index": "java", "_id": "17233226", "rating": 0},
]

I want to remove the last comma so that output looks like

[
{"_index": "java", "_id": "15194804", "rating": 0},
{"_index": "java", "_id": "18264178", "rating": 0},
{"_index": "java", "_id": "16225177", "rating": 1},
{"_index": "java", "_id": "16445238", "rating": 0},
{"_index": "java", "_id": "17233226", "rating": 0}
]

Here is my code

with open(folder   "/"   str(a[i])   ".json", 'w') as fp:
    fp.write("[\n")
    for i in range(len(ratings)):
        x = json.dumps(ratings[i])
        fp.write("%s,\n" % x)
    fp.write("]\n")
fp.close()

CodePudding user response:

If you want to have the last line without a comma

with open(folder   "/"   str(a[i])   ".json", 'w') as fp:
    fp.write("[\n")
    for i in range(len(ratings) - 1):
       x = json.dumps(ratings[i])
       fp.write("%s,\n" % x)
   fp.write("%s\n" % ratings[-1])
   fp.write("]\n")
fp.close()

CodePudding user response:

This would get the last line to have no comma

with open(folder   "/"   str(a[i])   ".json", 'w') as fp:
    fp.write("[\n")
    for i in range(len(ratings) - 1):
       x = json.dumps(ratings[i])
       fp.write("%s,\n" % x)
   fp.write("%s\n" % json.dumps(ratings[-1]))
   fp.write("]\n")
fp.close()
  • Related