0

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()
  • 4
    What does your `ratings` list look like? Because it seems that you could just do `json.dumps(ratings)` (no need for a `for` loop) or even better, `json.dump(ratings, fp)`. The json module understands properly a list of dictionaries. If you want to make it "pretty" in your file (with newlines and such), you can take a look to this other question: https://stackoverflow.com/q/12943819/289011 – Savir Oct 23 '22 at 20:02
  • `fp.write(',\n'.join(json.dumps(ratings[i])))` – cards Oct 23 '22 at 20:10
  • @BorrajaX I had to use a specific layout as I was working with ranking documents with ElasticSearch. While `json.dump()` was giving me the result, it was on just one single line. Nevertheless, I solved it with the help of other! – insanely_a_ Oct 24 '22 at 01:22

2 Answers2

0

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()
Chinny84
  • 956
  • 6
  • 16
  • This was very helpful but the last line had single quotes instead of double which I wanted. Nevertheless, I changed a bit of your answer to get the desired result. – insanely_a_ Oct 24 '22 at 01:19
0

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()