Issue converting list of dicts into string using json.dumps

I have list with dictionary of objects and want to convert the list into string.

i tried json.dumps(transactions, sort_key=True) and it just returns though the list is not empty and I can iterate the list and print the dict.

Any help would be appreciated.

Can you show the object? What you are trying should just work if the object is a list of dictionaries with supported datatypes. If you had unsupported objects, it would raise an error, not return an empty string.

>>> import json
>>> list_of_dicts = [
... {"a": 1, "b": 2, "c": 3},
... {"color": "red", "flower": "rose", "furniture": "chair"}
... ]
>>> json.dumps(list_of_dicts, sort_keys=True)
'[{"a": 1, "b": 2, "c": 3}, {"color": "red", "flower": "rose", "furniture": "chair"}]'
transactions has been declared as list and it looks like:
transactions[0]  
{'message': {'sender': 'A', 'receiver': 'B', 'value': 20, 'txt_metadata': '', 'priority': 2}, 'signature': b'ikNXm3JHqeikiXSPu/DAukvJjKkoJG4okSnn8JRfEVYlymHXhL7rY4gC8YBuJuiUhf5qPZfs9GpDPrOvdPVpJh1Kol8rd1eBH7PCTA71fx3ao8VCX7ZZONw39p8VIHTP0Jf6LbrJhXI6JCajQwgjlwpqYIhQLcIrzowFfUB8x92CPicj6bnuxnwwY8bWXE1Iyfwu2HHcfjCFTUuihtliOjcVhfTXo/lH5VW5xbhUKOb8O5SREqfV0lyyKjcUVeAaolTRoWT3v+7qnFSmYbjssPkpGRUEW1/z0eR8R9lxlIL94xb/cMBYH2FERk7PK23Bu9zzFlv5RzH4Jx7cnT6yRg=='}

One of the values in there is a bytes object which is not handled by default. json.dumps should throw an error on that. Can you encode that data? It still doesn’t explain why you would get an empty list.

>>> json.dumps(b'a byte string')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/export/apps/python/3.9/lib/python3.9/json/__init__.py", line 231, in dumps
    return _default_encoder.encode(obj)
  File "/export/apps/python/3.9/lib/python3.9/json/encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "/export/apps/python/3.9/lib/python3.9/json/encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "/export/apps/python/3.9/lib/python3.9/json/encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable
1 Like