How to append list entries to a JSON file through a for loop?

Question:

In the following code, I am trying to append every oth element to a JSON file:

title = []  # api_result['search_results']['title']
asin = []  # api_result['search_results']['asin']
link = []  # api_result['search_results']['link']
categories = []  # api_result['search_results']['categories'][0]['name']
image_url = []  # api_result['search_results']['image']
rating = []
rating_total = []
price = []  # apit_result['prices'][0]['value']
top_positive_review = []
top_positive_review_rating = []
top_critical_review = []
top_critical_review_rating = []
ratings_total_filtered = []  # apit_result['']
reviews_total_filtered = []
reviews_total = []
reviews = []

for o in range(len(title)):
    with open("metadata.jsonl", "w+") as outfile:
        entry = {
                'title': title[o],
                'asin': asin[o],
                'link': link[o],
                'categories': categories[o],
                'image_url': image_url[o],
                'rating': rating[o],
                'rating_total': rating_total[o],
                'price': price[o],
                'top_positive_review': top_positive_review[o],
                'top_positive_review_rating': top_positive_review_rating[o],
                'top_critical_review': top_critical_review[o],
                'top_critical_review_rating': top_critical_review_rating[o],
                'ratings_total_filtered': ratings_total_filtered[o],
                'reviews_total_filtered': reviews_total_filtered[o],
                'reviews_total': reviews_total[o],
                'reviews': reviews[o]}

I take that this isn’t the proper way of doing this. Basically, I want entries like this in the metadata.jsonl file:

{"title":"some title", "asin":"ABCDEF", ...}
{"title":"another title", "asin":"GHIJKL", ...}
...

Where am I going wrong?

Asked By: oo92

||

Answers:

Opening the file must be done only once with the with open block, otherwise it opens and closes the file at each iteration.

Thereafter, just wrap at each iteration.

Look at this code:

import json

# I am assuming your data in this form
title = ['title_0', 'title_1']
link = ['link_0', 'link_1']

with open("metadata.jsonl", "w") as file:
    for o in range(len(title)):
        entry = {
            'title': title[o],
            'link': link[o],
        }
        json_object = json.dumps(entry, ensure_ascii=False)  # on line json
        file.write(json_object)
        file.write("n")

output will be:

{"title": "title_0", "link": "link_0"}
{"title": "title_1", "link": "link_1"}
Answered By: Giuseppe La Gualano
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.