Reputation: 421
I have a For loop that extracts objects from your database query. Now I'm looking for a way to add these objects to an existing JSON string.
My list looks like this:
i = [(2, 23322323, 'object1name', 'example1'),(3, 2323232, 'object2name', 'example2'),(4, 12312312, 'object3name','example3')]
My For loop looks like this:
count = 1
for item in i:
object = item[2], item[3]
print("Object",count, item[2], item[3])
count = count + 1
My JSON String looks like this:
payload = json.dumps({'intent': 'test', 'message': message, 'url':imageURL})
I would like to have the following JSON output:
payload = json.dumps({'intent': 'test', 'message': message, 'url':imageURL, 'objetc1':object1, 'object2': object2})
I have tried to add the objects with:
payload['object'] = item[2], item[3]
But unfortunately I don't know how to add all objects and additionally the ascending numbering so Object1, Object2 and so on.
Thanks for your help.
Upvotes: 0
Views: 3364
Reputation: 298
Since json has dumped the value into payload, note payload is of type string. Need to convert payload to type dictionary to add elements.
# Loads payload back to dictionary
p = json.loads(payload)
# Add objects accordingly as per below
for index, item in enumerate(i):
p['object' + str(index)] = item[2], item[3]
Upvotes: 1
Reputation: 140
First of all, you do not need to keep track of the count. This is because python has a useful enumerate
function which returns both the item in the list and its position. So instead, you can do something like this:
fruits=['Apple', 'Banana', 'Mango']
for i, fruit in enumerate(fruits):
print(i, fruit)
This will give an output like:
0 Apple
1 Banana
2 Mango
So now that you have the count, you can use the count to keep track of the object count in your json key.
fruits=['Apple', 'Banana', 'Mango']
d={}
for i, fruit in enumerate(fruits):
d['fruit'+str(i)]=fruit
d
This is going to give an output like:
{'fruit0': 'Apple', 'fruit1': 'Banana', 'fruit2': 'Mango'}
Just replace fruits with the items in your database and you are good to go!
Upvotes: 2
Reputation: 21275
Try this:
for index, item in enumerate(i):
payload['object' + str(index)] = item
Upvotes: 0
Reputation: 624
I don't know what is your object structure but i think this will help you.
a={'intent': 'test', 'message': 'message', 'url':'imageURL'}
i=["ssdds","rajkot","baroda"]
count = 1
for item in range(len(i)):
a["object"+str(item+1)]=i[item]
print(a)
Upvotes: 0