Search code examples
pythonjsonserializationsimplejsonjsonserializer

Python list, tuple and dictionary to JSON?


What's the best way of displaying this as JSON?

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

My partial solution:

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)

Provides:

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

Would putting the args list in kwargs—e.g.: under an args key—be the only solution?


Solution

  • If you're just looking for valid JSON, you can put those values into a top-level array:

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

    Which yields:

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