【问题标题】:How to convert JSON array of key-value pairs to JSON object?如何将键值对的 JSON 数组转换为 JSON 对象?
【发布时间】:2014-05-26 03:10:44
【问题描述】:

我从网站上得到如下数据:

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

我只显示了我需要的数据。如何将其转换为 json,例如:

{u'mail@example.com': 74, u'mail2@example.com': 1, u'mail3@example.com': 1, ...}

我可以一个一个地读取元素:

if response.get('rows'):
    total = 0
    for row in response.get('rows'):
        total += int(row[1])
        logging.info(row[0]+": "+row[1])

但不确定下一步应该做什么。不要认为我应该只生成字符串。

【问题讨论】:

  • 不应该手动生成 JSON。创建相关的 Python 结构(即字典,使用转换),然后让您的 JSON 库将其转回。

标签: python json google-app-engine python-2.7 simplejson


【解决方案1】:

像这样:

>>> first_json = { 'rows':[['mail@example.com', '74'],['mail2@example.com','1'],['mail3@example.com','1']]}
>>> second_json = {item[0]: item[1] for item in first_json['rows']}
>>> second_json
{'mail@example.com': '74', 'mail2@example.com': '1', 'mail3@example.com': '1'}
>>>

您必须使用loads() 将上述数据字符串加载为jsonfirst_json 假定它可以作为 json 对象使用。然后如上计算second_json后,使用second_json上的dumps()得到输出json

编辑

看起来您正在计算特定电子邮件的电子邮件总数。在这种情况下,我会使用defaultdict

from collections import defaultdict

second_json = defaultdict(int)
for item in first_json['rows']:
    second_json[item[0]] += int(item[1])

然后按照上面的说明打印出second_json

【讨论】:

  • 字典比 json 多
【解决方案2】:

您需要创建一个字典并用行的内容填充它:

d = {}
for row in response.get('rows'):
    d[row[0]] = row[1]

那么,如果你想要一个 json 字符串表示:

json.dumps(d)

【讨论】:

    【解决方案3】:
    bbb = {}
    aaa = {
       u'rows':[
        [
          u'mail@example.com',
          u'74'
        ],
        [
          u'mail2@example.com',
          u'1'
        ],
        [
          u'mail3@example.com',
          u'1'
        ],
      ],
    }
    
    for item in aaa['rows']:
        bbb[item[0]] = item[1]
    
    print bbb
    
    >>> {u'mail@example.com': u'74', u'mail2@example.com': u'1', u'mail3@example.com': u'1'}
    

    【讨论】:

      猜你喜欢
      • 2016-03-18
      • 2013-05-03
      • 2022-11-01
      • 2021-03-10
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多