vesoft-inc / nebula-python

Client API of Nebula Graph in Python
193 stars 78 forks source link

How to convert the data returned from client into JSON? #71

Closed sliontc closed 3 years ago

sliontc commented 3 years ago

I want to convert the data from client into JSON in order to provide ability of web service.

CoreJa commented 3 years ago

Hey @sliontc, how did you manage it? I tried something like this:

json.dumps(query_resp, default=lambda x: getattr(x, '__dict__', str(x)))

But the result contains something like this: "column_names": ["b\'Name\'"], since nebula-python returns bytes and str() will turn bytes into b'something'.

I'm now building a dict using those field and convert it to JSON, but it's somehow to annoying.

Is there a clean and easy way to do so?

sliontc commented 3 years ago
def print_value(column_names, rows):
    output_table = prettytable.PrettyTable()
    output_table.field_names = column_names
    for row in rows:
        value_list = []
        for col in row.columns:
            if col.getType() == ttypes.ColumnValue.__EMPTY__:
                print('ERROR: type is empty')
                return
            elif col.getType() == ttypes.ColumnValue.BOOL_VAL:
                value_list.append(col.get_bool_val())
            elif col.getType() == ttypes.ColumnValue.INTEGER:
                value_list.append(col.get_integer())
            elif col.getType() == ttypes.ColumnValue.ID:
                value_list.append(col.get_id())
            elif col.getType() == ttypes.ColumnValue.STR:
                value_list.append(col.get_str().decode('utf-8'))
            elif col.getType() == ttypes.ColumnValue.DOUBLE_PRECISION:
                value_list.append(col.get_double_precision())
            elif col.getType() == ttypes.ColumnValue.TIMESTAMP:
                value_list.append(col.get_timestamp())
            else:
                print('ERROR: Type unsupported')
                return
        output_table.add_row(value_list)
    print(output_table)