不期速成 日拱一卒 不期速成 日拱一卒
首页
技术
测试
分类
标签
归档
关于
首页
技术
测试
分类
标签
归档
关于
  • Hello Docker
  • 二进制文件安装Docker指南
  • Docker网桥导致网络故障分析
  • 使用Docker部署Python开发调试运行环境
  • Habor-轻量化容器服务自动部署工具
  • 当开发团队开始用Docker,测试团队应该做什么?
  • 如何把应用服务手动注册到Systemd
  • 探究inode耗尽导致的no space left on device报错原因
  • PyCharm远程开发配置攻略
  • 视频推流方案
  • Prometheus&Grafana打造性能测试监控服务
  • Pythoner的vim
  • RobotFramework字符转译之坑
  • JSONSchema常用关键字语法手册
  • 根据JSON Schema生成JSON样例数据
  • 一图看懂正则表达式
  • SQL中LIMIT和IFNULL的使用
  • 基于Druid的接口测试自动化方案
  • 技术
2021-01-07

根据JSON Schema生成JSON样例数据

完成此目标分两步走

  1. 根据Schema定义解析推理JSON结构
  2. 根据数据定义生成随机数据

当前需求为根据YAPI导出的api.json文件来生成每个接口请求参数的样例数据, YAPI导出的请求参数的json schema定义有个特点:不严谨 --- 没有声明参数的数据值的内容要求,只有数据类型要求,因此我们生成样例数据随机生成即可,没有什么限制。

第一步我们经过精准的搜索,找到开源的轮子,直接使用,第二部代码简单实现下即可。

上代码。

#!/usr/bin/env python
# coding: utf-8
# @Time     : 2021/1/7 16:21
# @Author   : guoqun X2590
# @FileName : json_schema2json.py
# @Project  : JSchema2py

"""
使用说明
pip install jschema2py
"""


from jschema2py import build_class

import json


class JsonSchema2Json:
    """
    根据给定的JSON SCHEMA结构,随机赋值,生成json样例数据
    """
    def __init__(self):
        self.__string_sample = "I_am_a_string_data"
        self.__number_sample = 123
        self.__boolean_sample = True
        self.__array_string_sample = ["one_string", "two_string"]
        self.__array_number_sample = [1, 2, 3]
        self.__array_boolean_sample = [True, False]

    @staticmethod
    def pre_process_yapi_schema(schema_string):
        """
        将yapi提供的schema字符串进行预处理
        :param schema_string:
        :return:
        """
        __top_level = json.loads(schema_string)
        content_dict = __top_level['schema']
        __title = "one default title"
        content_dict['title'] = __title
        return content_dict

    def generate_sample_json(self, schema_dict):
        """
        生成样例json数据
        :param schema_dict:
        :return:
        """
        sample = build_class(schema_dict)()
        properties = schema_dict['properties']
        for __key, __value in properties.items():
            if __value['type'] == 'string':
                sample.__setattr__(__key, self.__string_sample)
            if __value['type'] == 'number':
                sample.__setattr__(__key, self.__number_sample)
            if __value['type'] == 'boolean':
                sample.__setattr__(__key, self.__boolean_sample)
            if __value['type'] == 'array':
                if __value['items']['type'] == 'number':
                    sample.__setattr__(__key, self.__array_number_sample)
                if __value['items']['type'] == 'string':
                    sample.__setattr__(__key, self.__array_string_sample)
                if __value['items']['type'] == 'boolean':
                    sample.__setattr__(__key, self.__array_boolean_sample)
        return str(sample)


if __name__ == '__main__':
    yapi_test_data = '''{"schema":{"$schema":"http://json-schema.org/draft-04/schema#","type":"object","properties":{"proType":{"type":"string","description":"属性类型"},"proValue":{"type":"string","description":"属性值"},"startTime":{"type":"string","description":"开始时间"},"endTime":{"type":"string","description":"结束时间"},"warnSources":{"type":"array","items":{"type":"number"},"description":"轨迹预警来源"}},"required":["proType","proValue"]},"required":true}'''
    js2j = JsonSchema2Json()
    schema = js2j.pre_process_yapi_schema(yapi_test_data)
    sample_data = js2j.generate_sample_json(schema)
    print(sample_data)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#JSON
上次更新: 7/26/2026, 3:17:15 PM
JSONSchema常用关键字语法手册
一图看懂正则表达式

← JSONSchema常用关键字语法手册 一图看懂正则表达式→

最近更新
01
测试覆盖度量全景图
11-30
02
Prism测试覆盖度量
11-30
03
AITDBClient使用文档
11-15
更多文章>
Theme by Vdoing | Copyright © 2021-2026 toddlerya | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式