使用Python转换为JSON的对象列表 [英] List of objects to JSON with Python

查看:671
本文介绍了使用Python转换为JSON的对象列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a problem converting Object instances to 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实例的列表.

In list_name I have a list of Object instances.

json_string返回,例如:

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

但是我只想要1个JSON字符串,并且所有信息都在列表中:

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

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

推荐答案

您可以使用列表推导来生成字典列表,然后进行转换:

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])

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

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

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 marshmallow to 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)

这篇关于使用Python转换为JSON的对象列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆