Python列表,元组和字典到JSON?

Posted

技术标签:

【中文标题】Python列表,元组和字典到JSON?【英文标题】:Python list, tuple and dictionary to JSON? 【发布时间】:2013-02-23 17:39:54 【问题描述】:

将其显示为 JSON 的最佳方式是什么?

'foo': 'bar'
[1,2,3,4,5]

我的部分解决方案:

import json

def json_tuple(*args, **kwargs):   
    if args:
        if kwargs:
            return json.dumps(args), json.dumps(kwargs)
        return json.dumps(args)

    return json.dumps(kwargs)

提供:

>>> json_tuple(1,2,3,4,5, **'foo': 'bar')
('[1, 2, 3, 4, 5]', '"foo": "bar"')

args 列表放在kwargs 中(例如:在args 键下)是唯一的解决方案吗?

【问题讨论】:

【参考方案1】:

如果您只是在寻找有效的 JSON,您可以将这些值放入***数组中:

import json

def jsonify(*args, **kwargs):
    return json.dumps((args, kwargs))  # Tuples are faster to create

产量:

'[[1, 2, 3, 4, 5], "foo": "bar"]'

【讨论】:

啊,太简单了。谢谢:)【参考方案2】:

我的“丑陋”解决方案:

import json

def jsonify(*args, **kwargs):   
    if args:
        kwargs.update('args': args)

    return json.dumps(kwargs)

提供:

>>> jsonify(1,2,3,4,5, **'foo': 'bar')
'"foo": "bar", "args": [1, 2, 3, 4, 5]'

【讨论】:

如果有arg kwarg 将失败。

以上是关于Python列表,元组和字典到JSON?的主要内容,如果未能解决你的问题,请参考以下文章

python自学笔记13:元组和字典的操作

2-1Python列表元组和字典

python第三节列表元组和字典

Python学习之路——Python基础之基本数据类型(列表元组和字典)

Python列表,元组,集合,字典的区别和相互

python的列表,元组和字典简单介绍