Python dumps将对象作为字符串而不是json传递
我有一个类和一个函数可以将类对象更改为json:Python dumps将对象作为字符串而不是json传递,python,json,flask,Python,Json,Flask,我有一个类和一个函数可以将类对象更改为json: class AuthorizedUser: def __init__(self, authorized, comsi, given_name, access_role): self.authorized = authorized self.comsi = comsi self.given_name = given_name self.access_role = acc
class AuthorizedUser:
def __init__(self, authorized, comsi, given_name, access_role):
self.authorized = authorized
self.comsi = comsi
self.given_name = given_name
self.access_role = access_role
def to_json(self):
return json.dumps(self, default=lambda o: o.__dict__)
我还有一个json,它可以工作:
authorized_user_json = {
'authorized': authorized_user.authorized,
'comsi': authorized_user.comsi,
'given_name': authorized_user.given_name,
'access_role': authorized_user.access_role
}
结果:
{'authorized': True, 'comsi': None, 'given_name': None, 'access_role': 'standard_user'}
但当我使用:
authorized_user_json_ss = authorized_user.to_json()
结果是:
<SecureCookieSession {'current_user': '{"authorized": true, "comsi": null, "given_name": null, "access_role": "standard_user"}'}>
为什么在使用to_json函数时会有额外的引号?json是非结构化数据的文本表示形式,它使数据从一种语言传递到另一种语言变得更容易 在Python中,JSON只是一个存储在文本中的dict 这不是JSON,而是一个python DICT:
authorized_user_json = {
'authorized': authorized_user.authorized,
'comsi': authorized_user.comsi,
'given_name': authorized_user.given_name,
'access_role': authorized_user.access_role
}
因为如果你没有额外的引号,它会是一个dict,而不是字符串?应该是这样的,因为json.dumps返回stringOh,好的。你能告诉我一个正确的方向吗?我想实现什么?很明显,我不想回报你,我不确定我是否理解你想要实现的目标。是否要将对象转换为字典?然后不要使用dumpsThank。我理解!