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 OverflowYou 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)
As ZdaR's post illustrates, to create a json, you need to build the corresponding Python data structure (lists for json arrays, dictionaries for json objects) and serialize it at the end. So the question is almost the same as how to create a list in a loop, because after creating the list, what remains is serialization which is as simple as json.loads(data).
The task in the OP can be done in two loops:
data = [{'Title': line.getText(strip=True)} for line in games_html.findAll('a')]
for i, line in enumerate(games_html.findAll('div', class_="product_score")):
data[i]['Score'] = line.getText(strip=True)
# serialize to json array
j = json.dumps(data)
# or write to a file
with open('data.json', 'w') as f:
json.dump(data, f)
How to create a json file from list in python? - Stack Overflow
How do I create json array of objects using python - Stack Overflow
Python: Convert a list of python dictionaries to an array of JSON objects - Stack Overflow
Create json array using list in python - Stack Overflow
... 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)); ...
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"
}
}
Convert the lists to list of dictionaries and dump this to the file
arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100, 3400, 200]
with open('file.json', 'w') as file:
json.dump([{'user': id, 'wallet amount': amount} for id, amount in zip(arr_of_id_by_user, arr_of_wallet_amount)], file)
file.json
[{"user": 1, "wallet amount": 100}, {"user": 2, "wallet amount": 3400}, {"user": 3, "wallet amount": 200}]
Another simple solution, using enumerate:
import json
arr_of_id_by_user = [1, 2, 3]
arr_of_wallet_amount = [100,3400,200]
jsonfile=[]
for index, value in enumerate(arr_of_id_by_user):
jsonfile.append({
"user": value,
"waller_amount": arr_of_wallet_amount[index]
})
print (json.dumps(jsonfile, indent=4))
You are adding the exact same dictionary to the list. You should create a new dictionary for each item in the list:
json.dumps([dict(mpn=pn) for pn in lst])
As explained by others (in answers) you should create a new dictionary for each item on the list elsewhere you reference always the same dictionary
import json
part_nums = ['ECA-1EHG102','CL05B103KB5NNNC','CC0402KRX5R8BB104']
def json_list(list):
lst = []
for pn in list:
d = {}
d['mpn']=pn
lst.append(d)
return json.dumps(lst)
print json_list(part_nums)
[{"mpn": "ECA-1EHG102"}, {"mpn": "CL05B103KB5NNNC"}, {"mpn": "CC0402KRX5R8BB104"}]
hey there, i want to create a json file from 2 lists (label, data) where every item has different properties.
label[x] = ["Part Number", "name", "weight", ...] data[x] = ["33882", "screw", "23g", ...] label[y] = ["Part Number", "name", "color", ...] data[y]= ["33882", "screw", "red", ...]
It should look something like this:
{
"item x" : {
"Part Number": "33882",
"name": "screw",
"weight: "23g
},
"item y: " {
"Part Number": "47342",
"name": "hammer",
"color: "red,
"label: "data
},
}if have no idea how to achiev this since my python skills are pretty basic and i couldn't find any examples which helped me.
would somebody give me a hint or example please?
You can achieve this by using built-in json module
import json
arrayJson = json.dumps([{"email": item} for item in pyList])
Try to Google this kind of stuff first. :)
import json
array = [1, 2, 3]
jsonArray = json.dumps(array)
By the way, the result you asked for can not be achieved with the list you provided.
You need to use python dictionaries to get json objects. The conversion is like below
Python -> JSON
list -> array
dictionary -> object
And here is the link to the docs https://docs.python.org/3/library/json.html
Just adding onto alexce's response, you can easily convert the restructured data into JSON:
import json
json.dumps(result)
There are some potential security concerns with top-level arrays. I'm not sure if they're still valid with modern browsers, but you may want to consider wrapping it in an object.
import json
json.dumps({'results': result})
To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehension producing a list of dictionaries:
>>> from pprint import pprint
>>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
... ['String 11']]
>>> def chunks(l, n):
... """Yield successive n-sized chunks from l."""
... for i in range(0, len(l), n):
... yield l[i:i+n]
...
>>>
>>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))}
for chunk in chunks(l, 7)]
>>> pprint(result)
[{'title1': 'String 1',
'title2': 'String 2',
'title3': 'String 3',
'title4': 'String 4',
'title5': 'String 5',
'title6': 'String 6',
'title7': 'String 7'},
{'title1': 'String 8',
'title2': 'String 9',
'title3': 'String 10',
'title4': 'String 11'}]