如何解决mgp.Vertex.properties无法JSON序列化的问题?
解决Memgraph中mgp.Vertex.properties无法JSON序列化的问题
mgp.Vertex.properties返回的是Memgraph自定义的属性容器对象,并非Python原生可序列化类型,直接传入json.dumps()会触发序列化错误,最优解决方式是将其转换为Python原生的数据结构(字典或键值对列表)。
方法1:转换为Python字典
遍历属性容器的键,构建原生字典后再序列化:
import json import mgp @mgp.read_proc def serialize_vertex(ctx: mgp.ProcCtx, vertex: mgp.Vertex) -> mgp.Record(result=str): # 转换为原生字典 vertex_props = {key: vertex.properties[key] for key in vertex.properties} vertex_data = { "id": vertex.id, "labels": list(vertex.labels), "properties": vertex_props } return mgp.Record(result=json.dumps(vertex_data))
方法2:转换为键值对列表
如果需要将属性以列表形式存储,可生成包含键值对的列表:
import json import mgp @mgp.read_proc def serialize_vertex(ctx: mgp.ProcCtx, vertex: mgp.Vertex) -> mgp.Record(result=str): # 转换为键值对列表 props_list = [{"key": key, "value": vertex.properties[key]} for key in vertex.properties] vertex_data = { "id": vertex.id, "labels": list(vertex.labels), "properties": props_list } return mgp.Record(result=json.dumps(vertex_data))
注意事项
- 确保属性值本身是JSON可序列化类型(字符串、数字、布尔值等),若存在自定义类型,需额外编写转换逻辑。
- 直接遍历
vertex.properties即可获取所有属性键,通过vertex.properties[key]可安全获取对应属性值。
内容的提问来源于stack exchange,提问作者KateLatte
相关产品推荐
相关产品推荐

