Search code examples
pythonjsongoogle-app-enginepython-2.7simplejson

How to convert JSON array of key-value pairs to JSON object?


I get the data like below from the website:

{
  ...
  u'rows':[
    [
      u'mail@example.com',
      u'74'
    ],
    [
      u'mail2@example.com',
      u'1'
    ],
    [
      u'mail3@example.com',
      u'1'
    ],
    ...
  ],

I've shown just the data I need. How can I convert it to json like:

{u'mail@example.com': 74, u'mail2@example.com': 1, u'mail3@example.com': 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.


Solution

  • 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)