在最大深度2或3中查找具有所有允许的结构组合的JSON示例



我编写了一个处理JSON对象的程序。现在我想核实一下我是否遗漏了什么。

是否存在所有允许的JSON结构组合的JSON示例?类似这样的东西:

{
    "key1" : "value",
    "key2" : 1,
    "key3" : {"key1" : "value"},
    "key4" : [
                [
                    "string1",
                    "string2"
                ],
                [
                    1,
                    2
                ],
                ...
    ],
    "key5" : true,
    "key6" : false,
    "key7" : null,
    ...
}

正如您在http://json.org/在右边,JSON的语法不是很难,但我有几个例外,因为我忘记了处理一些可能的结构组合。例如,在数组中可以有"字符串、数字、对象、数组、true、false、null",但我的程序无法处理数组中的数组,直到遇到异常。所以一切都很好,直到我得到了这个数组中有数组的有效JSON对象。

我想用一个JSON对象(我正在寻找(来测试我的程序。在这次测试之后,我想确信我的程序能够毫无例外地处理地球上所有可能有效的JSON结构。

我不需要嵌套深度5左右。我只需要嵌套深度2或最大值3的东西。使用嵌套了所有允许的基类型的所有基类型,在此基类型内。

您想过对象中的转义字符和对象吗?

{
    "key1" : {
                 "key1" : "value",
                 "key2" : [
                              "String1",
                              "String2"
                 ],
             },
    "key2" : ""This is a quote"",
    "key3" : "This contains an escaped slash: \",
    "key4" : "This contains accent charachters: u00eb u00ef",
}

注:u00ebu00ef分别为。characterëandï

选择一种支持json的编程语言。尝试加载json,失败时异常的消息是描述性的。

示例:

Python:

import json, sys;
json.loads(open(sys.argv[1]).read())

生成:

import random, json, os, string
def json_null(depth = 0):
    return None
def json_int(depth = 0):
    return random.randint(-999, 999)
def json_float(depth = 0):
    return random.uniform(-999, 999)
def json_string(depth = 0):
    return ''.join(random.sample(string.printable, random.randrange(10, 40)))
def json_bool(depth = 0):
    return random.randint(0, 1) == 1
def json_list(depth):
    lst = []
    if depth:
        for i in range(random.randrange(8)):
            lst.append(gen_json(random.randrange(depth)))
    return lst
def json_object(depth):
    obj = {}
    if depth:
        for i in range(random.randrange(8)):
            obj[json_string()] = gen_json(random.randrange(depth))
    return obj
def gen_json(depth = 8):
    if depth:
        return random.choice([json_list, json_object])(depth)
    else:
        return random.choice([json_null, json_int, json_float, json_string, json_bool])(depth)
print(json.dumps(gen_json(), indent = 2))

最新更新