Convert JSON to JSON Schema draft 4 compatible with Swagger 2.0

前端 未结 3 1475
南旧
南旧 2021-01-04 03:03

I\'ve been given some JSON files generated by a REST API with plenty of properties.

I\'ve created a Swagger 2.0 definition for this API and need to give it the corre

3条回答
  •  太阳男子
    2021-01-04 03:47

    You can directly goto https://bikcrum.github.io/Swagger-JSON-Schema-In-YAML_webversion/ for online conversion.

    I wrote following python script to generate JSON schema in YAML format (preserving key order) that is used in Swagger.

    import json
    
    # input file containing json file
    with open('data.json') as f:
        json_data = json.load(f)
    
    # json schema in yaml format
    out = open('out.yaml','w')
    
    def gettype(type):
        for i in ['string','boolean','integer']:
            if type in i:
                return i
        return type
    
    def write(string):
        print(string)
        out.write(string+'\n')
        out.flush()
    
    def parser(json_data,indent):
        if type(json_data) is dict:
            write(indent + 'type: object')
            if len(json_data) > 0:
                write(indent + 'properties:')
            for key in json_data:
                write(indent + '  %s:' % key)
                parser(json_data[key], indent+'    ')
        elif type(json_data) is list:
            write(indent + 'type: array')
            write(indent + 'items:')
            if len(json_data) != 0:
                parser(json_data[0], indent+'  ')
            else:
                write(indent + '  type: object')
        else:
            write(indent + 'type: %s' % gettype(type(json_data).__name__))
    
    parser(json_data,'')
    

    Update: If you want YAML with sorted keys (which is by default) use YAML library

    import json
    import yaml
    
    # input file containing json file
    with open('data.json') as f:
        json_data = json.load(f)
    
    # json schema in yaml format
    
    def gettype(type):
        for i in ['string','boolean','integer']:
            if type in i:
                return i
        return type   
    
    def parser(json_data):
        d = {}
        if type(json_data) is dict:
            d['type'] = 'object'
            for key in json_data:
                d[key] = parser(json_data[key])
            return d
        elif type(json_data) is list:
            d['type'] = 'array'
            if len(json_data) != 0:
                d['items'] = parser(json_data[0])
            else:
                d['items'] = 'object'
            return d
        else:
            d['type'] = gettype(type(json_data).__name__)
            return d
    
    p = parser(json_data)
    with open('out.yaml','w') as outfile:
        yaml.dump(p,outfile, default_flow_style=False)
    

提交回复
热议问题