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)
... 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"}]
Edit your code to:
image_list = {}
# list of image_details
image_list["image_details"] = []
#query for getting objects
images = Image_history.objects.all()
#looping through object and storing in dictionary
for image in images:
image_dict = {}
image_dict['type']= image.image_type
image_dict['timestamp']= image.last_updated_timestamp
#appending all those objects in loop to image_list
image_list["image_details"].append(image_dict)
Your are editing the same dictionary object, you just have to create new one at each iteration. Dictionary (created using dict or {} ) is mutable objects in python, I suggest you read more about mutability in python. And I suggest more compact way to build your list, using list comprehensions:
image_list["image_details"] = [
{
'type': image.image_type,
'timestamp': image.last_updated_timestamp
} for image in images
]
Note: you can create immutable dictionary in python, but this off-topic.
You are mutating the same image_dict object, which in turn modifies existing references to that object (i.e. previous dictionary values).
Why do you avoid constructing a new dict? It is the only way to create separate dictionaries.
Alternatively you can move image_dict = {} into the for loop:
...
for image in images:
image_dict = {}
image_dict['type']= image.image_type
...
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.)
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
var names = ["bob", "joe", "jim"];
var nameObjs = names.map(function(item) {
return { name: item };
});
You can then use JSON.stringfy on nameObjs if you actually need JSON.
Here's a fiddle
Why not this?
// Get your values however rou want, this is just a example
var names = ["bob", "joe", "jim"];
//Initiate a empty array that holds the results
var nameObjs = [];
//Loop over input.
for (var i = 0; i < names.length; i++) {
nameObjs.push({"name": names[i]}); //Pushes a object to the results with a key whose value is the value of the source at the current index
}