在Python

时间:2018-02-26 06:07:31

标签: python json

我是Python新手,非常感谢您的帮助。 我得到了这个反对象:

Counter({1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10, 10: 
        10})

每个密钥实际上是一个userId,其值为number_of_posts

所以我最终需要将这个计数器对象转换为像这样的JSON:

{ 
    “user”:
        {
            id: int
            number_of_posts: int
        }
}

请指教.. 谢谢 拉菲

2 个答案:

答案 0 :(得分:0)

这可能会有所帮助。我正在迭代你的字典并创建所需的结构。

from  collections import Counter
a = Counter({1: 10, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 7: 10, 8: 10, 9: 10, 10:10})
d = {"user": []}
for k,v in a.items():
    d["user"].append({"id": k, "number_of_posts": v})

print(d)

<强>输出:

{'user': [{'number_of_posts': 10, 'id': 1}, {'number_of_posts': 10, 'id': 2}, {'number_of_posts': 10, 'id': 3}, {'number_of_posts': 10, 'id': 4}, {'number_of_posts': 10, 'id': 5}, {'number_of_posts': 10, 'id': 6}, {'number_of_posts': 10, 'id': 7}, {'number_of_posts': 10, 'id': 8}, {'number_of_posts': 10, 'id': 9}, {'number_of_posts': 10, 'id': 10}]}

答案 1 :(得分:-1)

生成所需的格式,然后将其转换为JSON类型

import json

ret = {}
li = []
for key, value in dic.items():
    ret['id'] = key
    ret['number'] = value
    li.append(ret)
    ret = {}
ret['user'] = li
return json.dumps(ret)