【问题标题】:Create dynamic json object in python在python中创建动态json对象
【发布时间】:2017-06-22 14:41:03
【问题描述】:

我有一个字典,其中包含多个键和值,并且值还包含键、值对。我没有得到如何在 python 中使用这个字典创建动态 json。这是字典:

image_dict = {"IMAGE_1":{"img0":"IMAGE_2","img1":"IMAGE_3","img2":"IMAGE_4"},"IMAGE_2":{"img0":"IMAGE_1", "img1" : "IMAGE_3"},"IMAGE_3":{"img0":"IMAGE_1", "img1":"IMAGE_2"},"IMAGE_4":{"img0":"IMAGE_1"}}  

我的预期结果是这样的:

{
  "data": [
    {
      "image": {
        "imageId": {
          "id": "IMAGE_1"
        },
        "link": {
          "target": {
            "id": "IMAGE_2"
          },
          "target": {
            "id": "IMAGE_3"
          },
          "target": {
            "id": "IMAGE_4"
          }
        }
      },
      "updateData": "link"
    },
       {
      "image": {
        "imageId": {
          "id": "IMAGE_2"
        },
        "link": {
          "target": {
            "id": "IMAGE_1"  
          },
          "target": {
            "id": "IMAGE_3"  
          }
        }
      },
      "updateData": "link"
    },
    {
      "image": {
        "imageId": {
          "id": "IMAGE_3"
        },
        "link": {
          "target": {
            "id": "IMAGE_1"  
          },
          "target": {
            "id": "IMAGE_2"  
          }
        }
      },
      "updateData": "link"
    } ,
    {
      "image": {
        "imageId": {
          "id": "IMAGE_4"
        },
        "link": {
          "target": {
            "id": "IMAGE_1"  
          }
        }
      },
      "updateData": "link"
    } 
  ]
}  

我试图解决它,但我没有得到预期的结果。

result = {"data":[]}

for k,v in sorted(image_dict.items()):
    for a in sorted(v.values()):
        result["data"].append({"image":{"imageId":{"id": k},
                                        "link":{"target":{"id": a}}},"updateData": "link"})
print(json.dumps(result, indent=4))

【问题讨论】:

  • json 部分在这里完全(嗯,大部分)无关紧要,你的问题是“我如何将这个源字典转换成那个目标字典。
  • 是的,你说得对@brunodesthuilliers
  • @rajendrapawar,您预期的 json 无效。 dict .. "link": { "target": { "id": "IMAGE_2" }, "target": { "id": "IMAGE_3" }, "target": { "id": "IMAGE_4" } .. 中不能有重复的键
  • @RomanPerekhrest 是的,我知道,但我只想这样
  • @rajendrapawar,你无法获得无效的结构,至少在 Python 中没有

标签: python json list dictionary dynamically-generated


【解决方案1】:

在 Python 字典中,不能有 2 个具有相同键的值。所以你不能有多个目标都称为“目标”。所以你可以索引它们。另外我不知道这个问题与动态对象有什么关系,但这是我开始工作的代码:

import re
dict_res = {}
ind = 0
for image in image_dict:
    lin_ind = 0
    sub_dict = {'image' + str(ind): {'imageId': {image}, 'link': {}}}
    for sub in image_dict[image].values():
        sub_dict['image' + str(ind)]['link'].update({'target' + str(lin_ind): {'id': sub}})
        lin_ind += 1
    dict_res.update(sub_dict)
    ind += 1
dict_res = re.sub('target\d', 'target', re.sub('image\d', 'image', str(dict_res)))
print dict_res

【讨论】:

  • 除了索引号还有什么不同?
  • 你可以把它变成一个字符串。并使用 re 函数。我对为您执行此操作的代码进行了编辑。
猜你喜欢
  • 2016-10-02
  • 2019-10-21
  • 1970-01-01
  • 1970-01-01
  • 2013-04-15
  • 2014-12-13
  • 2023-02-09
  • 2017-05-23
  • 2019-07-27
相关资源
最近更新 更多