打印json

2022/05/20 Offer 共 1606 字,约 5 分钟

打印json

需求是类似json formatter 那样 递归展示json.

python判断是否是数组 可以这样isinstance(list, x)

包括string, bool, 也可以。

# return the json string, it returns error it is not a json
def json_print_handle(obj):
    if is_map(obj) or is_arr(obj):
        return "\n".join(json_print(obj))
    # not a valid json
    return "error"


# convert json string list
def json_print(obj):
    ans = []
    if is_normal_data(obj):
        if obj is None:
            # for None
            ans.append("null")
        elif isinstance(obj, str):
            # for string
            ans.append('"%s"' % obj)
        else:
            # for integer, float
            ans.append('%s' % obj)

    elif is_arr(obj):
        ans.append("[")
        for i, v in enumerate(obj):
            t = json_print(v)
            for _, l in enumerate(t):
                if i < len(obj) - 1:
                    ans.append("\t%s," % l)
                else:
                    ans.append("\t%s" % l)
        ans.append("]")
    elif is_map(obj):
        ans.append("{")
        for i, k in enumerate(obj):
            v = obj[k]
            t = json_print(v)
            ans.append('\t"%s":' % k)
            ans[-1] += t[0]
            for j in range(1, len(t)):
                l = t[j]
                ans.append('\t%s' % l)
            if i < len(obj) - 1:
                ans[-1] += ","
        ans.append("}")

    return ans


if __name__ == '__main__':
    cases = [
        # list, normal type
        [
            ["a", "b", 3, 1.2],
            r'''[
    "a",
    "b",
    3,
    1.2
]'''
        ],
        # list, normal type, contains null
        [
            ["a", "b", 3, None],
            r'''[
	"a",
	"b",
	3,
	null
]'''
        ],
        # map, normal type
        [
            {"a": 1},
            r'''{
    "a":1
}'''
        ],
        # map, multiple keys
        [
            {"a": 1, "b": 2},
            r'''{
    "a":1,
    "b":2
}'''
        ],
        # map, list value
        [
            {"a": []},
            r'''{
	"a":[
	]
}'''
        ],
        # map, map value
        [
            {"a": {"b": 3}},
            r'''{
	"a":{
		"b":3
	}
}'''
        ],
        # map, map value of map value
        [
            {"a": {"b": {"c": 3}}},
            r'''{
	"a":{
		"b":{
			"c":3
		}
	}
}'''
        ],
        # map, map value of map value + normal value
        [
            {"a": {"b": {"c": 3}, "z": "k"}, "x": 1.2},
            r'''{
	"a":{
		"b":{
			"c":3
		},
		"z":"k"
	},
	"x":1.2
}'''
        ],
        # list, map value + list value
        [
            [{"a": 3, "b": "z"}, [1, 2, 3]],
            r'''[
	{,
		"a":3,,
		"b":"z",
	},
	[
		1,
		2,
		3
	]
]'''
        ],
    ]
    for case in cases:
        params, expect = case
        actual = json_print_handle(params)
        print(expect)
        print(actual)
		# 可以assert断言

Search

    Table of Contents