【问题标题】:json.dumps generates a string and returning it as dict is making a string inside another string, how to avoid it and get just a single stringjson.dumps 生成一个字符串并返回它,因为 dict 在另一个字符串中创建一个字符串,如何避免它并只获得一个字符串
【发布时间】:2020-03-10 05:26:26
【问题描述】:
class_object = ModelClass(title=entity_object['title'], 
                            entities_definition_key=entity_object['entities_definition_key'],
                            orderId=entity_object['orderId'],uid = json.dumps( uuid.uuid4(), 
                            cls=UUIDEncoder))

ModelClass 是 mongoengine 模型类

json_output = class_object.serializing_method()
final_list.append(json_output)
another_class_object = AnotherModelClass(workflowId=body['workflowId'],entities_list=final_list)
another_class_object.save()

save() 到 mongodb

final_dict={}
final_dict['entities_list'] = another_class_object.entities_list
return HttpResponse(json.dumps({'entity_definition_dict':entity_definition_dict}))          

输出-{'uid': "\"74b1900ccfbd44234563805ac0279d\""}

【问题讨论】:

  • 你为什么要多次调用json.dumps()
  • 第一个 json.dumps() 仅用于 uid,在第二个 json.dumps() 中,我正在转储具有除 uid 之外的多个值的 dict
  • 多次使用json.dumps() 是导致我认为您的问题的原因。每次调用它时,都会得到一个字符串,而不是字典。所以一个字符串被传递给下一个调用,而不是你想要的字典。
  • 我知道问题是 json.dumps(),但我正在寻找解决方案
  • 第一次不需要序列化。

标签: python django string response mongoengine


【解决方案1】:

我不知道您为什么需要在 UUID 上调用 json.dumps()。它会导致你所有的问题,我无法想象它会解​​决什么问题。

class_object = ModelClass(
    ...,
    uid = uuid.uuid4().hex,
)

【讨论】:

  • 它说“TypeError: 'UUID' 类型的对象不是 JSON 可序列化的”
  • 这就是我序列化它的原因
  • type(uuid.uuid4().hex) == str。您是否添加了.hex 位。
猜你喜欢
  • 2022-11-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 2023-03-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多