Reputation: 20429
I get the data like below from the website:
{
...
u'rows':[
[
u'[email protected]',
u'74'
],
[
u'[email protected]',
u'1'
],
[
u'[email protected]',
u'1'
],
...
],
I've shown just the data I need. How can I convert it to json like:
{u'[email protected]': 74, u'[email protected]': 1, u'[email protected]': 1, ...}
I can read elements one by one:
if response.get('rows'):
total = 0
for row in response.get('rows'):
total += int(row[1])
logging.info(row[0]+": "+row[1])
But not sure what should be done next. Don't think I should generate just the string.
Upvotes: 1
Views: 8868
Reputation: 11370
bbb = {}
aaa = {
u'rows':[
[
u'[email protected]',
u'74'
],
[
u'[email protected]',
u'1'
],
[
u'[email protected]',
u'1'
],
],
}
for item in aaa['rows']:
bbb[item[0]] = item[1]
print bbb
>>> {u'[email protected]': u'74', u'[email protected]': u'1', u'[email protected]': u'1'}
Upvotes: 0
Reputation: 12092
Like this:
>>> first_json = { 'rows':[['[email protected]', '74'],['[email protected]','1'],['[email protected]','1']]}
>>> second_json = {item[0]: item[1] for item in first_json['rows']}
>>> second_json
{'[email protected]': '74', '[email protected]': '1', '[email protected]': '1'}
>>>
You will have to load the above data string as a json
using loads()
. first_json
assumes that it is available to it as a json object. Then after computing the second_json
as above, use the dumps()
on second_json
to get the output json
EDIT
Looks like you are computing total number of emails for a particular email. In that case I would use a defaultdict
.
from collections import defaultdict
second_json = defaultdict(int)
for item in first_json['rows']:
second_json[item[0]] += int(item[1])
Then print out the second_json
as explained above.
Upvotes: 0
Reputation: 39403
You need to create a dict and populate it with the content of the rows:
d = {}
for row in response.get('rows'):
d[row[0]] = row[1]
Then, if you want a json string representation:
json.dumps(d)
Upvotes: 2