使用Python的JSON对象列表

2024-05-23 21:56:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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

list_name中,我有一个Object实例列表。

json_string返回,例如:

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

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

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

Tags: 实例namejsoncity列表stringobjectlist
3条回答

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

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

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.

执行转换很简单:

import jsonpickle

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

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

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

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

def obj_dict(obj):
    return obj.__dict__

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

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

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

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)

相关问题 更多 >