sonic-net / sonic-py-swsssdk

Python SONiC switch state service sdk
Other
13 stars 86 forks source link

could sonic-db-cli return JSON string for hgetall ? #100

Closed Junchao-Mellanox closed 3 years ago

Junchao-Mellanox commented 3 years ago

Sometimes, sonic-mgmt need check values in redis db by calling "sonic-db-cli $DB HGETALL $KEY". And it would be great if the output of such command can be parsed to a python dictionary easily.

However, sonic-db-cli now return raw string for hgetall comamnd. For example:

admin@r-leopard-01:~$ sonic-db-cli CONFIG_DB HGETALL "TELEMETRY|gnmi"
{'client_auth': 'false', 'log_level': '2', 'port': '50051'}

Python json module cannot parse such string to a dictionary:

{'client_auth': 'false', 'log_level': '2', 'port': '50051'}

I would suggest to change the following code in sonic-db-cli from:

        if resp is None:
            print()
        elif isinstance(resp, list):
            print("\n".join(resp))
        else:
            print(resp)

to

        if resp is None:
            print()
        elif isinstance(resp, list):
            print("\n".join(resp))
        elif isinstance(resp, dict):
            json.dumps(resp)
        else:
            print(resp)

Any thought?

Junchao-Mellanox commented 3 years ago

As we could use ast.literal_eval to de-serialize dict from string, I am closing this issue.