Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
5.4 kB
2
Indexable
Never
import json
import ast
import re

def fromJsonToField(input, className):
    fields = ''
    keys = input.keys()
    for key in keys:
        if type(input[key]) == type(""):

            if ('_' in str(key) or str(key).startswith('$')):
                varName = toCamel(key)
                fields += '@JsonKey(name: "{}") final String? {};\n'.format(key,
                                                                            varName)
            else:
                varName = toCamel(key)
                fields += 'final String? ' + toCamel(key) + ';\n'
        elif type(input[key]) == type(1):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final int? {} ;\n'.format(key,
                                                                          toCamel(key))
            else:
                fields += 'final int? ' + toCamel(key) + ';\n'
        elif type(input[key]) == type(1.0):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final double? {} ;\n'.format(key,
                                                                             toCamel(key))
            else:
                fields += 'final double? ' + toCamel(key) + ';\n'
        elif type(input[key]) == type(True):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final bool? {} ;\n'.format(key,
                                                                           toCamel(key))
            else:
                fields += 'final bool? ' + toCamel(key) + ';\n'
        elif type(input[key]) == type({}):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final {}? {};\n'.format(key,
                                                                        toCamel(key).title(), toCamel(key))
                fromJsonToField(input[key], toCamel(key).title())
            else:
                fields += 'final {}? {};\n'.format(
                    toCamel(key).title(), toCamel(key))
                fromJsonToField(input[key], key.title())
        elif type(input[key] == type([])):
            if ('_' in str(key) or str(key).startswith('$')):
                fields += '@JsonKey(name: "{}") final List<{}>? {};\n'.format(
                    key, toCamel(key).title(), toCamel(key))
                fromJsonToField(ast.literal_eval(
                    str(list(input[key])[0])), toCamel(key).title())
            else:
                fields += 'final List<{}>? {};\n'.format(
                    toCamel(key).title(), toCamel(key))
                fromJsonToField(ast.literal_eval(
                    str(list(input[key])[0])), toCamel(key).title())

    print(template.replace('{className}', className).replace(
        '{field}', fields.replace('"$', '"\\$')))


template = """
@freezed
class {className} with _${className} {
    const factory {className}({
       {field}
    }) = _{className};

    factory {className}.fromJson(Map<String, dynamic> json) => _${className}FromJson(json);
}
"""


def toCamel(snake_str):
    components = snake_str.split('_')
    # We capitalize the first letter of each component except the first one
    # with the 'title' method and join them together.
    if components[0] != '':
        x = components[0] + ''.join(x.title() for x in components[1:])
    else:
        x = components[1] + ''.join(x.title() for x in components[2:])
    i = 0
    while (x[i] == '$'):
        i+=1
    return x[i:]

def toSnake (camel_input):
    words = re.findall(r'[A-Z]?[a-z]+|[A-Z]{2,}(?=[A-Z][a-z]|\d|\W|$)|\d+', camel_input)
    return '_'.join(map(str.lower, words))


def getFieldName(key, type):
    if ('_' in str(key) or str(key).startswith('$')):
        return '@JsonKey(name: "{}") final {} {};\n'.format(key, key, key)
    else:
        return 'final {} {};\n'.format(key, key)

jsonString = """
{
  "msg": "changed",
  "collection": "stream-room-messages",
  "id": "id",
  "fields": {
    "event_name": "c4K9WSMxQWXrKJ22e",
    "args": [
      {
        "_id": "azS4jsNHGsB7wcpjY",
        "t": "ru",
        "rid": "c4K9WSMxQWXrKJ22e",
        "ts": {
          "$date": 1652860408908
        },
        "msg": "giaptt-01-rikkeisoft.com",
        "u": {
          "_id": "5GnTy6hDwXBZwMF4N",
          "username": "tungnt7-01-rikkeisoft.com",
          "name": "Nguyễn Thanh Tùng"
        },
        "groupable": false,
        "unread": true,
        "_updatedAt": {
          "date": 1652860408908
        }
      }
    ]
  }
}
""".replace("true", "True").replace("false", "False")


if __name__ == '__main__':

    # # print(baseJson)
    # # print(baseJson.keys())
    className = "MessageModel"
    baseJson = ast.literal_eval(jsonString)
    print("import 'package:freezed_annotation/freezed_annotation.dart';")
    print("{}.freezed.dart", toSnake(className))
    print("{}.g.dart", toSnake(className))

    fromJsonToField(baseJson, className)

    # print(ast.literal_eval('''{'_id': 'azS4jsNHGsB7wcpjY', 't': 'ru', 'rid': 'c4K9WSMxQWXrKJ22e', 'ts': {'$date': 1652860408908}, 'msg': 'giaptt-01-rikkeisoft.com', 'u': {'_id': '5GnTy6hDwXBZwMF4N', 'username': 'tungnt7-01-rikkeisoft.com', 'name': 'Nguyễn Thanh Tùng'}, 'groupable': False, 'unread': True, '_updatedAt': {'date': 1652860408908}}'''))