使用 Python 转换为 JSON 的对象列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26033239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:57:09  来源:igfitidea点击:

List of objects to JSON with Python

pythonjsonobjectserialization

提问by pedro

I have a problem converting Objectinstances to JSON:

我在将Object实例转换为 JSON 时遇到问题:

ob = Object()

list_name = scaping_myObj(base_url, u, number_page)

for ob in list_name:
   json_string = json.dumps(ob.__dict__)
   print json_string

In list_nameI have a list of Objectinstances.

list_name我有一个Object实例列表。

json_stringreturn, for example:

json_string返回,例如:

{"city": "rouen", "name": "1, 2, 3 Soleil"}
{"city": "rouen", "name": "Maman, les p'tits bateaux"}

But I would like just 1 JSON string with all the info in a list:

但我只想要 1 个 JSON 字符串,其中包含列表中的所有信息:

[{"city": "rouen", "name": "1, 2, 3 Soleil"}, {"city": "rouen", "name": "Maman, les p'tits bateaux"}]

采纳答案by Martijn Pieters

You can use a list comprehension to produce a list of dictionaries, then convert that:

您可以使用列表理解来生成字典列表,然后将其转换为:

json_string = json.dumps([ob.__dict__ for ob in list_name])

or use a defaultfunction; json.dumps()will call it for anything it cannot serialise:

或使用default函数;json.dumps()将调用它无法序列化的任何内容:

def obj_dict(obj):
    return obj.__dict__

json_string = json.dumps(list_name, default=obj_dict)

The latter works for objects inserted at any level of the structure, not just in lists.

后者适用于在结构的任何级别插入的对象,而不仅仅是在列表中。

Personally, I'd use a project like marshmallowto handle anything more complex; e.g. handling your example data could be done with

就个人而言,我会使用像棉花糖这样的项目来处理任何更复杂的事情;例如处理您的示例数据可以完成

from marshmallow import Schema, fields

class ObjectSchema(Schema):
    city = fields.Str()
    name = fields.Str()

object_schema = ObjectSchema()
json_string = object_schema.dumps(list_name, many=True)

回答by Steven Wolfe

Another possible solution to this problem is jsonpicklewhich can be used to transform any Python object into JSON (not just simple lists).

此问题的另一个可能解决方案是jsonpickle,它可用于将任何 Python 对象转换为 JSON(不仅仅是简单的列表)。

From the jsonpicklehome page:

jsonpickle主页:

jsonpickle is a Python library for serialization and deserialization of complex Python objects to and from JSON. The standard Python libraries for encoding Python into JSON, such as the stdlib's json, simplejson, and demjson, can only handle Python primitives that have a direct JSON equivalent (e.g. dicts, lists, strings, ints, etc.). jsonpickle builds on top of these libraries and allows more complex data structures to be serialized to JSON. jsonpickle is highly configurable and extendable–allowing the user to choose the JSON backend and add additional backends.

jsonpickle 是一个 Python 库,用于将复杂的 Python 对象与 JSON 进行序列化和反序列化。用于将 Python 编码为 JSON 的标准 Python 库,例如 stdlib 的 json、simplejson 和 demjson,只能处理具有直接 JSON 等效项的 Python 原语(例如,dicts、lists、strings、ints 等)。jsonpickle 构建在这些库之上,并允许将更复杂的数据结构序列化为 JSON。jsonpickle 是高度可配置和可扩展的——允许用户选择 JSON 后端并添加额外的后端。

Performing a transformation is simple:

执行转换很简单:

import jsonpickle

class JsonTransformer(object):
    def transform(self, myObject):
        return jsonpickle.encode(myObject, unpicklable=False)

回答by Eric Romrell

Similar to @MartijnPieters' answer, you can use the json.dumps defaultparameter with a lambda, if you don't want to have to create a separate function: json.dumps(obj, default = lambda x: x.__dict__)

与@MartijnPieters 的回答类似default,如果您不想创建单独的函数,您可以将 json.dumps参数与 lambda 一起使用: json.dumps(obj, default = lambda x: x.__dict__)