【问题标题】:Python list, tuple and dictionary to JSON?Python列表,元组和字典到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 键下)是唯一的解决方案吗?

【问题讨论】:

    标签: python json serialization simplejson jsonserializer


    【解决方案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 将失败。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-24
    • 1970-01-01
    • 2020-05-10
    • 2014-03-31
    • 1970-01-01
    • 2017-09-11
    相关资源
    最近更新 更多