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
🌐
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.
🌐
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.
🌐
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=(',', ':'))
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
October 27, 2022 - This is how to convert a list to a JSON array in Python. To convert a list to a JSON array is called serialization. Learn how to serialize and deserialize a list with this in-depth article. Let’s get started! ... PIP vs. PIP3: Difference? You learn the structure of JSON objects and why they’re ...
Find elsewhere
🌐
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)
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.)

🌐
DataCamp
datacamp.com › tutorial › json-data-python
Python JSON Data: A Guide With Examples | DataCamp
December 3, 2024 - Learn how to work with JSON in Python, including serialization, deserialization, formatting, optimizing performance, handling APIs, and understanding JSON’s limitations and alternatives.
🌐
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 ...
🌐
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
🌐
JSON Schema
json-schema.org › understanding-json-schema › reference › array
JSON Schema - array
In JSON, each element in an array may be of a different type. ... In Python, "array" is analogous to the list or tuple type, depending on usage.