首页 > 解决方案 > 如何使用 python 将记录或列表转换为 JSON 格式?

问题描述

我正在尝试使用 Python 将列表转换为 JSON。查询的结果如下所示:

输出:

[<Record r=<Relationship id=106 nodes=(<Node id=71 labels=frozenset({'TBox'}) properties={'identifier': '', 'ontology_level': 'lower', 'neo4jImportId': '105', 'html_info': '', 'namespace': 'car', 'admin': '', 'description': 'remove', 'sing': '', 'pl': '', 'title': 'BMProcessor', 'version': 'v6.0'}>, <Node id=59 labels=frozenset({'TBox'}) properties={'identifier': '', 'ontology_level': 'lower', 'neo4jImportId': '93', 'html_info': '', 'namespace': 'car', 'admin': '', 'description': 'A DataProcessor which represents a ML algorithm', 'sing': '', 'pl': '', 'title': 'LearningProcessor', 'version': 'v6.0'}>) type='subclass_of' properties={}> b=<Node id=59 labels=frozenset({'TBox'}) properties={'identifier': '', 'ontology_level': 'lower', 'neo4jImportId': '93', 'html_info': '', 'namespace': 'car', 'admin': '', 'description': 'A DataProcessor which represents a ML algorithm', 'sing': '', 'pl': '', 'title': 'LearningProcessor', 'version': 'v6.0'}> n=<Node id=71 labels=frozenset({'TBox'}) properties={'identifier': '', 'ontology_level': 'lower', 'neo4jImportId': '105', 'html_info': '', 'namespace': 'car', 'admin': '', 'description': 'remove', 'sing': '', 'pl': '', 'title': 'BMProcessor', 'version': 'v6.0'}>>]

功能 :

def runQuery(query):
  pprint.pprint(connection.execute(query))

当我执行一个简单的json.dumps()它返回TypeError: Object of type is not JSON serializable

我想打印一个 JSON 格式。我该怎么做?

标签: pythonjsonneo4j

解决方案


你可以得到result.data()这是一本字典。

您还可以遍历游标中的记录并一一转换,并提取您想要的字段,这就是上面链接示例所做的 - 传递游标并使用blob['field']语法

def serialize_genre(genre):
    return {
        'id': genre['id'],
        'name': genre['name'],
    }

推荐阅读