-1

I am new in Python and would appreciate your help. I got this counter object :

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

Each key is actually a userId with a count number_of_posts as a value.

So what I finally need is to convert this counter object to a JSON like so :

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

Please advise.. Thanks Raffi

Shubhitgarg
  • 588
  • 6
  • 20
  • Probably duplicated of [Converting Dictionary to JSON in python](https://stackoverflow.com/questions/26745519/converting-dictionary-to-json-in-python) – pe-perry Feb 26 '18 at 06:20

2 Answers2

1

This might help. I am iterating over your dictionary and creating the required structure.

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)

Output:

{'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}]}
Rakesh
  • 81,458
  • 17
  • 76
  • 113
-1

Generate the required format, and then convert it to the JSON type

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)
ZHX
  • 51
  • 1
  • 1