Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert os.stat_result to a JSON that is an object?

I know that json.dumps can be used to convert variables into a JSON representation. Sadly the conversion of python3's class os.stat_result is an string consisting of an array representing the values of the class instance.

>>> import json
>>> import os
>>> json.dumps(os.stat('/'))
'[16877, 256, 24, 1, 0, 0, 268, 1554977084, 1554976849, 1554976849]'

I would however much prefer to have it convert the os.stat_result being converted to an JSON being an object. How can I achieve this?

It seems that the trouble is that os.stat_result does not have a .__dict__ thing.

seeing the result of this:

 >>> import os
 >>> str(os.stat('/'))
 'os.stat_result(st_mode=16877, st_ino=256, st_dev=24, st_nlink=1, st_uid=0, st_gid=0, st_size=268, st_atime=1554977084, st_mtime=1554976849, st_ctime=1554976849)'

makes me hope there is a swift way to turn an python class instance (e.g. `os.stat_result") into a JSON representation that is an object.

which while is JSON, but the results are

like image 671
humanityANDpeace Avatar asked Feb 03 '23 19:02

humanityANDpeace


1 Answers

as gst mentioned, manually would be this:

def stat_to_json(fp: str) -> dict:
    s_obj = os.stat(fp)
    return {k: getattr(s_obj, k) for k in dir(s_obj) if k.startswith('st_')}
like image 94
a.k Avatar answered Feb 06 '23 08:02

a.k