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)
Videos
... 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"
}
}
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"}]
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()
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.)
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)
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": ""
}
]
}
Take a look at the json module. More specifically the 'Decoding JSON:' section.
import json
import requests
response = requests.get() # api call
users = json.loads(response.text)
for user in users:
print(user['id'])
You can try like below to get the values from json response:
import json
content=[{
"username": "admin",
"first_name": "",
"last_name": "",
"roles": "system_admin system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335509393,
"create_at": 1511335500662,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "pbjds5wmsp8cxr993nmc6ozodh"
}, {
"username": "chatops",
"first_name": "",
"last_name": "",
"roles": "system_user",
"locale": "en",
"delete_at": 0,
"update_at": 1511335743479,
"create_at": 1511335743393,
"auth_service": "",
"email": "[email protected]",
"auth_data": "",
"position": "",
"nickname": "",
"id": "akxdddp5p7fjirxq7whhntq1nr"
}]
for item in content:
print("Name: {}\nEmail: {}\nID: {}\n".format(item['username'],item['email'],item['id']))
Output:
Name: admin
Email: [email protected]
ID: pbjds5wmsp8cxr993nmc6ozodh
Name: chatops
Email: [email protected]
ID: akxdddp5p7fjirxq7whhntq1nr
You should be able to condense the whole thing down to just this:
import json
tables = ["a", "b", "c", "d"]
data = {}
for t in tables:
results = sf.query("select id from %s" % t)["records"]
data[t] = [r["id"] for r in results]
with open("Dataset.json", "w") as f:
json.dump(data, f)
You can simply create a dictionary containing the values you are after and then convert it to json using json.dumps
import json
data = {}
data['a'] = ["12","34","23"]
data['b'] = ["13","14","45"]
json_data = json.dumps(data)
print json_data