使用Python测试JSON字段

时间:2017-09-01 05:18:02

标签: python json

有没有办法使用Python来测试JSON数据的所有可能的字段值组合?例如,我有一些JSON数据,并在括号中包含了每个字段的可能字段值:

{
"userPrompt": {
     "enabled": false, (true or false)
     "clickable": true, (true, false)
     "imageUrl": "http://www.dummyimage.com/300x250.jpg", 
     "imageWidth": 10, (value must be an integer)
     "imageHeight": 10, (value must be an integer)
     "showStatus": true (true or false)
 },

"showVideo": {
    "enabled": false, (true or false)
    "play": false (true or false)
 },
 "playerType": [ (array must include "flash", "html5", or both)
 "flash",
 "html5"
 ]

我真的只想找到一种方法来迭代所有场的可能性,并打印出每个场组合的完整JSON结构。希望这是有道理的;我很感激帮助。谢谢。

2 个答案:

答案 0 :(得分:5)

您可以使用itertools.product()生成一堆组合。

import itertools

some_ints = (1, 5)
bools = (True, False)

choices = [
    bools,
    bools,
    some_ints,
    some_ints,
    bools,
    bools,
    bools,
    (['flash'], ['html'], ['flash', 'html']),
]

for tup in itertools.product(*choices):
    print(tup)

然后使用生成的元组构建所需的dicts / JSON。

答案 1 :(得分:1)

要扩展@ FMc的方法,您需要修改8个字段,即假设imageUrl未更改。使用itertools.product()是一种以单一简单迭代方式实现多个嵌套循环的紧凑方法。每次迭代将导致所有字段的值的一个组合。第一次迭代将为您的字段提供以下元组值:

(False, False, 10, 10, False, False, False, ['flash'])

接下来,您需要使用所有新值更新JSON对象。一种方法是使用update()分配新值,如下所示:

import itertools
import json

data = """{
"userPrompt": {
     "enabled": false,
     "clickable": true,
     "imageUrl": "http://www.dummyimage.com/300x250.jpg", 
     "imageWidth": 10,
     "imageHeight": 10,
     "showStatus": true
 },

"showVideo": {
    "enabled": false,
    "play": false
 },
 "playerType": ["flash", "html5"]
 }
 """

jd = json.loads(data)
ints = (10, 20, 30)
bools = (False, True)
choices = [bools, bools, ints, ints, bools, bools, bools, (['flash'], ['html'], ['flash', 'html'])]

for tup in itertools.product(*choices):
    jd['userPrompt'].update({
        'enabled': tup[0], 
        'clickable': tup[1], 
        'imageWidth': tup[2],
        'imageHeight': tup[3],
        'showStatus' : tup[4]})
    jd['showVideo'].update({
        'enabled' : tup[5],
        'play' : tup[6]})
    jd['playerType'] = tup[7]

    print(jd)

所以第一次迭代会显示以下内容:

{
    u'userPrompt': {
        u'showStatus': False, 
        u'imageUrl': u'http://www.dummyimage.com/300x250.jpg', 
        u'enabled': False, 
        u'imageHeight': 10, 
        u'imageWidth': 10, 
        u'clickable': False
    }, 

    u'playerType': ['flash'], 

    u'showVideo': {
        u'play': False, 
        u'enabled': False
    }
}