You need to maintain two lists for scores and titles and append all the data to those lists, instead of printing, and then zip those lists along with list comprehension to get the desired output as :

import json
scores, titles = [], []
for line in games_html.findAll('div', class_="product_score"):
    scores.append(line.getText(strip=True))

for line in games_html.findAll('a'):
    titles.append(line.getText(strip=True))

score_titles = [{"Title": t, "Score": s} for t, s in zip(titles, scores)]
print score_titles
# Printing in JSON format
print json.dumps(score_titles)
Answer from ZdaR on Stack Overflow
🌐
ReqBin
reqbin.com › json › python › uzykkick › json-array-example
Python | What is JSON Array?
The following is an example of an array of JSON booleans: ... A JSON object is similar to a JavaScript object. We can also create a JSON array containing many objects, and then we can iterate over this array or use "[]" square brackets to get the desired object.
🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - This option allows you to specify the separators used in the output JSON string. The separators parameter takes a tuple of two strings, where the first string is the separator between JSON object key-value pairs, and the second string is the separator between items in JSON arrays.
🌐
Stack Overflow
stackoverflow.com › questions › 38176182 › how-to-create-an-array-of-objects-in-json-using-python
How to create an array of objects in JSON, using python? - Stack Overflow
May 23, 2017 - I actually think this question is a bit different, since it is asking how to take any number of lists. At least, it is not an exact duplicate. ... As pointed out below my answer is incorrect because lists do not have names but you could try to combine it with this answer to set up something that aims at what you are trying to do ... names = [a.__name__ for a in arrays] objs = [] For arrs in zip(arrays): objs.append({"array_" + n: val for n, val in zip(names, arrs)})
🌐
Stack Overflow
stackoverflow.com › questions › 70578104 › how-do-i-create-json-array-of-objects-using-python
How do I create json array of objects using python - Stack Overflow
Python obviously has no way to know that you are writing a list of objects when you are writing them one at a time ... so just don't. cells = soup.table('td') cities = [] for cell in cells[:-2]: cities.append({"country": str(cells[count].getText()), "city": str(cells[count].next_sibling.getText())}) json.dump(cities, cities_list)
🌐
GeeksforGeeks
geeksforgeeks.org › python › build-a-json-object-in-python
Build a Json Object in Python - GeeksforGeeks
July 23, 2025 - In this example, the json.loads() function is used to parse a JSON-formatted string json_string into a Python dictionary named data. The resulting dictionary is then printed, representing the decoded JSON data. ... import json json_string = '{"name": "GFG", "age": 19, "isStudent": true}' data = json.loads(json_string) print(type(json_string)) print(data) ... Encoder function is defined that's used for encoding sets and converting to list. A json object named 'gfg' is created as a set.
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
The json.dumps() method has parameters to make it easier to read the result: Use the indent parameter to define the numbers of indents: ... You can also define the separators, default value is (", ", ": "), which means using a comma and a space ...
Find elsewhere
Top answer
1 of 2
15

... the JSON array at the end of your answer is incorrect, but to generate an array, just give a list to json.dumps in Python. Something like json_data_list = []; ... ; json_data_list.append(json_data); ... print(json.dumps(json_data_list)); ...

2 of 2
2

Your JSON file is incorrect. Normally you must have a structure as:

{
    "key1": [
        {
            "id": "blabla",
            "name": "Toto"
        },
        {
            "id": "blibli",
            "name": "Tata"
        }
    ],
    "key2": {
        "id": "value"
    },
    "key3": "value"
}

So I think you have to change your JSON array for example as following:

{
    [
        {
            "id": 0,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        },
        {
            "id": 1,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        },
        {
            "id": 2,
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
        }
    ]
}

You can decide also to have not a list of dictionary as I proposed above but to use the ID value as key for each dictionary; in that case you have:

{
    "id0":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    },
    "id1":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    },
    "id2":{       
            "organizer": "Some Name",
            "eventStart": "09:30 AM",
            "eventEnd": "10:00 AM",
            "subject": "rental procedure",
            "attendees": "Some Name<br />Person 2<br />Person 3"
    }
}
🌐
Tech With Tech
techwithtech.com › home › converting list to json array in python: how to?
Converting List to JSON Array in Python: How To? - Tech With Tech
August 11, 2021 - After that you’ll get methods for converting a string or file into a Python object and the other way around. Python lists are the most similar structure to JSON arrays, so they are converted directly to JSON arrays by using the dumps method:
Top answer
1 of 3
2

make it this way:

def getTasks(filename):
    f = open(filename, 'r')
    a = open('tasksJSON', 'w')
    x = []
    d = xmltodict.parse(f)
    l = d.get('Project').get('Tasks').get('Task')
    for task in l:
        if (task['Name'] == 'dinner'):  #criteria for desirable tasks
            #j = json.dumps(task)
            x.append(task)
            #a.write (str(j))   
            #a.write(',')         

    a.write(json.dumps(x))
    f.close()
    a.close()
2 of 3
1

JSON doesn't allow extra commas at the end of an array or object. But your code adds such an extra comma. If you look at the official grammar here, you can only have a , before another value. And Python's json library conforms to that grammar, so:

>>> json.loads('[1, 2, 3, ]')
ValueError: Expecting value: line 1 column 8 (char 7)

To fix this, you could do something like this:

first = True
for task in l:
    if (task['Name'] == 'dinner'):  #criteria for desirable tasks
        if first:
            first = False
        else:
            a.write(',')
        j = json.dumps(task)
        a.write(str(j))   

On the other hand, if memory isn't an issue, it might be simpler—and certainly cleaner—to just add all of the objects to a list and then json.dumps that list:

output = []
for task in l:
    if (task['Name'] == 'dinner'):  #criteria for desirable tasks
        output.append(task)
a.write(json.dumps(output))

Or, more simply:

json.dump([task for task in l if task['Name'] == 'dinner'], a)

(In fact, even if memory is an issue, you can extend JSONEncoder, as shown in the docs, to handle iterators by converting them lazily into JSON arrays, but this is a bit tricky, so I won't show the details unless someone needs them.)

🌐
Stack Overflow
stackoverflow.com › questions › 51862285 › how-to-make-an-array-at-the-objects-json-field › 51958855
python - How to make an array at the object's JSON field? - Stack Overflow
REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ), 'DEFAULT_PARSER_CLASSES': ( 'rest_framework.parsers.JSONParser', ) } ... class FactorySerializer(serializers.ModelSerializer): class Meta: model = Factory fields = ['title', 'address'] ... class FactoryListView(generics.ListCreateAPIView): queryset = Factory.objects.all() serializer_class = FactorySerializer
Top answer
1 of 4
12

Here is the final working code

        pickup_dict = {}
        pickup_records=[]


        for tmpPickUp in pickup:
                pickup_date=tmpPickUp.pickup_date
                pickup_time=tmpPickUp.pickup_time

                pickup_id = tmpPickUp.id
                pickup_name=tmpPickUp.customer_name
                pickup_number=tmpPickUp.pieces
                print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
                record = {"name":pickup_name, "id":pickup_id,"number":pickup_number,"status":"1","time":"time"}
                print record
                pickup_records.append(record)

        pickup_dict["pickup"]=pickup_records


        return JsonResponse(pickup_dict)
2 of 4
2

I think you need to make sure you're declaring pickup_records as a list, and then check the way you're calling json.dumps.

pickup_records = []
for tmpPickUp in pickup:
    pickup_date=tmpPickUp.pickup_date
    pickup_time=tmpPickUp.pickup_time
    pickup_id = tmpPickUp.id
    pickup_name=tmpPickUp.customer_name
    pickup_number=tmpPickUp.pieces
    print pickup_date,pickup_time,pickup_id,pickup_name,pickup_number
    record = {"name":pickup_name, "id":pickup_id,"time":pickup_date,"number":pickup_number,"status":"1"}
    pickup_records.append(record)
pickup_records = json.dumps({'pickups': pickup_records}, indent=4) 
pickup_response={"pickup":pickup_records}
return HttpResponse(pickup_response, content_type="application/json")

UPDATE

I've run the following in a console - (I think the error must be with your TmpPickUp items) -

>>> import json
>>> records = []
>>> for i in ["","",""]:
...     record = {"name":i, "id":i,"time":i,"number":i,"status":i}
...     records.append(record)
... 
>>> print json.dumps({'pickups': records}, indent=4)
{
    "pickups": [
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }, 
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }, 
        {
            "status": "", 
            "time": "", 
            "number": "", 
            "name": "", 
            "id": ""
        }
    ]
}
🌐
Python Examples
pythonexamples.org › python-create-json
Python Create JSON
In this example, we will create JSON formatted string from a Python List. Python List will have dictionaries as items. import json myList = [{'a': 54}, {'b': 41, 'c':87}] jsonString = json.dumps(myList, indent=4) print(jsonString)
🌐
Stack Overflow
stackoverflow.com › questions › 70175479 › how-to-create-array-of-json-objects-with-multiple-values
python - How to create array of JSON objects with multiple values? - Stack Overflow
As written, this question is lacking some of the information it needs to be answered. If the author adds details in comments, consider editing them into the question. Once there's sufficient detail to answer, vote to reopen the question. Closed 4 years ago. ... I tried using an append to create a new array. However, either the created function returns an array with several objects and not an object with several values. ... def parse_json(self, data): file = 'vault.json' json = {} for obj in data: if 'EMAIL' in obj[0]: json.setdefault('EMAIL', []).append({obj[0]: obj[1]}) if 'TEST' in obj[0]: json.setdefault('TEST', []).append({obj[0]: obj[1]}) else: json.setdefault('VAULT', []).append({obj[0]: obj[1]}) with open(file, 'w') as f: dump(json, f, indent=2, separators=(',', ':'))
🌐
JSON Schema
json-schema.org › understanding-json-schema › reference › array
JSON Schema - array
However, the json module in the Python standard library will always use Python lists to represent JSON arrays. ... List validation: a sequence of arbitrary length where each item matches the same schema.
🌐
W3Schools
w3schools.com › js › js_json_arrays.asp
JSON Arrays
JSON Intro JSON Syntax JSON vs XML JSON Data Types JSON Parse JSON Stringify JSON Objects JSON Arrays JSON Server JSON PHP JSON HTML JSON JSONP JS jQuery