You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何解决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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 06:10:30