根据JSON Schema生成JSON样例数据
完成此目标分两步走
- 根据Schema定义解析推理JSON结构
- 根据数据定义生成随机数据
当前需求为根据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
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
上次更新: 7/26/2026, 3:17:15 PM