【问题标题】:Convert existing dictonary to JSON with Python使用 Python 将现有字典转换为 JSON
【发布时间】:2019-01-23 09:06:24
【问题描述】:

在我当前的 django 项目中,我构建了一个字典,其中包含一个元组,其中包含有关给定团队的数据。团队由具有子角色和分配给该特定团队的资源组成。

现在的问题是我需要将此字典转换为 JSON 格式,因为我想使用不同的 Google Charts 来可视化数据,但我不知道该怎么做。

这是字典中的一个例子:

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

我认为我可能需要遍历我的字典并构建 JSON 的每个部分,但不知道该怎么做。 尝试使用 json.dumps(data),但这只会给我一个错误,说“'set' 类型的对象不是 json 可序列化的”,我在这篇文章中读到了一些内容: Serializable

谁能给我一些建议?

【问题讨论】:

  • 那是不是字典,它是一个集合,注意{('Build Master', 50)},它是一个包含2元组的集合。没有等效的 JSON。
  • @WillemVanOnsem 啊,好吧,我以为我有一本字典可以用!
  • 您可以将其转换为字典,但最好先看看为什么它首先返回一组 2 元组。看起来不好建模。

标签: python json django dictionary google-visualization


【解决方案1】:

做这样的事情:

导入json data = {'Team Bobcat': {'Tom Bennett': {('Build Master', 50)}} {'Team Coffee': {'Garfield Foster': {('Scrum Master', 100)}} json_string = json.dumps(数据)

【讨论】:

  • 正是发生错误的地方:这个data包含一个set,它没有默认的序列化方式。
【解决方案2】:

希望对您有所帮助:

>>> 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'>

换句话说,你可以在{}的帮助下声明setdict,这取决于你在里面写的内容。

在此处了解更多信息:https://docs.python.org/3/tutorial/datastructures.html

要使您的数据可序列化,只需使用它即可:

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

例子:

>>> json.dumps({'Team Bobcat': {'Tom Bennett': ['Build Master', 50]}})
'{"Team Bobcat": {"Tom Bennett": ["Build Master", 50]}}'

【讨论】:

    【解决方案3】:

    你可以使用 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))
    

    【讨论】:

      猜你喜欢
      • 2011-01-29
      • 2023-03-16
      • 2014-02-26
      • 2018-05-04
      • 2021-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多