|
| 1 | +#!/usr/bin/python3 |
| 2 | +# coding:utf-8 |
| 3 | +import sys |
| 4 | +import io |
| 5 | +import json |
| 6 | +import collections |
| 7 | + |
| 8 | +sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') |
| 9 | + |
| 10 | +# 最终文件 |
| 11 | +save2File = [] |
| 12 | +classNames = [] |
| 13 | +result = [] |
| 14 | +# key className |
| 15 | +Result = collections.namedtuple("Result", ["key", "define", "name"]) |
| 16 | + |
| 17 | +inPutFile = "./json.json" |
| 18 | +outPutFile = "./model.txt" |
| 19 | + |
| 20 | + |
| 21 | +def getJsonDic(): |
| 22 | + with open(inPutFile, "r", encoding='utf-8') as f: |
| 23 | + d = json.load(f) |
| 24 | + return d |
| 25 | + |
| 26 | + |
| 27 | +def wirteString(string): |
| 28 | + with open(outPutFile, "w", encoding='utf-8') as f: |
| 29 | + f.write(string) |
| 30 | + |
| 31 | + |
| 32 | +def convetType(value, key): |
| 33 | + if isinstance(value, str): |
| 34 | + return "String" |
| 35 | + elif isinstance(value, float): |
| 36 | + return "Float" |
| 37 | + elif isinstance(value, bool): |
| 38 | + return "Bool" |
| 39 | + elif isinstance(value, int): |
| 40 | + return "Int" |
| 41 | + elif isinstance(value, list): |
| 42 | + return "[{0}]".format(key) |
| 43 | + elif isinstance(value, dict): |
| 44 | + return key |
| 45 | + elif not value: |
| 46 | + return "String" |
| 47 | + else: |
| 48 | + return "String" |
| 49 | + |
| 50 | + |
| 51 | +def realKey(key): |
| 52 | + return "%s" % (key.capitalize()) |
| 53 | + |
| 54 | + |
| 55 | +def proDict(dic, name=""): |
| 56 | + if name != "": |
| 57 | + classNames.append(name) |
| 58 | + |
| 59 | + for (key, value) in dic.items(): |
| 60 | + clsName = realKey(key) |
| 61 | + if isinstance(value, list): |
| 62 | + proDict(value[0], clsName) |
| 63 | + elif isinstance(value, dict): |
| 64 | + proDict(value, clsName) |
| 65 | + |
| 66 | + k = ' var {0}: {1}?'.format(key, convetType(value, clsName)) |
| 67 | + result.append(Result(key, k, name)) |
| 68 | + |
| 69 | + |
| 70 | +def process(data, name): |
| 71 | + name = realKey(name) |
| 72 | + if isinstance(data, list): |
| 73 | + proDict(data[0], name) |
| 74 | + elif isinstance(data, dict): |
| 75 | + proDict(data, name) |
| 76 | + |
| 77 | + return display() |
| 78 | + |
| 79 | + |
| 80 | +def display(): |
| 81 | + for cls in classNames: |
| 82 | + save2File.append("struct %s:Decodable {" % cls) |
| 83 | + for r in result: |
| 84 | + if r.name == cls: |
| 85 | + save2File.append(r.define) |
| 86 | + save2File.append("}") |
| 87 | + save2File.append("") |
| 88 | + save2File.append("") |
| 89 | + return save2File |
| 90 | + |
| 91 | + |
| 92 | +def getSaveString(): |
| 93 | + saveString = "" |
| 94 | + for s in save2File: |
| 95 | + saveString += s + "\n" |
| 96 | + return saveString |
| 97 | + |
| 98 | + |
| 99 | +jsonDic = getJsonDic() |
| 100 | +process(jsonDic, "Model") |
| 101 | +saveString = getSaveString() |
| 102 | +print(saveString) |
| 103 | +wirteString(saveString) |
0 commit comments