1

In my current django project I have built a dictionary, which has a tuple inside of it, that contains data about a given team. A team consists of resources that have a sub-role and allocation to that particular team.

The problem now is that I need to convert this dictionary to JSON-format because I want to use different Google Charts to visualize the data, and I can't figure out how to do that.

Here is a example from the dictonary:

{'Team Bobcat': {'Tom Bennett': {('Build Master', 50)}}
{'Team Coffe': {'Garfield Foster': {('Scrum Master', 100)}}

I think that I probably need to loop through my dictionary and build each part of the JSON, but not sure how to do that. Tried to use json.dumps(data), but that only game me a error saying "object of type 'set' is not json serializable", which I read something about in this post: Serializable

Can anyone give me any advice?

Vlok
  • 63
  • 2
  • 12
  • 1
    That is *not* a dictionary, it is a set, note the `{('Build Master', 50)}`, it is a set containing a 2-tuple. There is no JSON equivalent. – Willem Van Onsem Aug 16 '18 at 11:55
  • @WillemVanOnsem Ah okay, thought I had a dictionary to work with! – Vlok Aug 16 '18 at 11:56
  • 1
    You can *convert* it to a dictionary, but perhaps it is better to first look why this returned a set of 2-tuples in the first place. Looks like bad modelling. – Willem Van Onsem Aug 16 '18 at 11:57

3 Answers3

1

Hope this will help you:

>>> a = {2: 3, 4: 5}
>>> a
{2: 3, 4: 5}
>>> type(a)
<class 'dict'>
>>> 
>>> b = {2, 3, 4, 5}
>>> b
{2, 3, 4, 5}
>>> type(b)
<class 'set'>
>>> 
>>> c = {7}
>>> c
{7}
>>> type(c)
<class 'set'>
>>> 
>>> d = {}
>>> d
{}
>>> type(d)
<class 'dict'>

In other words, you can declare set or dict with the help of {} depending on what you write inside.

Read more about it here: https://docs.python.org/3/tutorial/datastructures.html

To make your data serializable, just use this instead:

{'Team Bobcat': {'Tom Bennett': ['Build Master', 50]}}
{'Team Coffe': {'Garfield Foster': ['Scrum Master', 100]}}

Example:

>>> json.dumps({'Team Bobcat': {'Tom Bennett': ['Build Master', 50]}})
'{"Team Bobcat": {"Tom Bennett": ["Build Master", 50]}}'
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
1

do something like this:

import json

data = {'Team Bobcat': {'Tom Bennett': {('Build Master', 50)}}
{'Team Coffee': {'Garfield Foster': {('Scrum Master', 100)}}

json_string = json.dumps(data)
Olamide226
  • 428
  • 6
  • 12
0

You can use JSONEncoder

import json 
class ComplexEncoder(json.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, set):
             return [el for el in obj]
         return json.JSONEncoder.default(self, obj)

print(json.dumps({'Team Coffe': {'Garfield Foster': {('Scrum Master', 100)}}}, cls=ComplexEncoder))
Rafał
  • 685
  • 6
  • 13