Created
June 18, 2019 05:00
-
-
Save myvyang/79a70884b7d64005c31d299af7fef41e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def json_structure(j): | |
""" | |
JSON有三种结构:字面值(int, bool, str), dict, list | |
为简化处理,将list通过转换视为dict结构,key为序号。 | |
["a", 1] -> {"0": "a", "1": 1} | |
这个函数返回json的结构信息,"值"会被丢弃。 | |
{"a": 1, "b": ["n", false]} | |
-> | |
{"a": 1, "b": {"0": "n", "1": false}} | |
-> | |
[ | |
("a", int), | |
("b", | |
[("0", str), ("1", bool)] | |
) | |
] | |
然后按key的字典序进行排序 | |
""" | |
if isinstance(j, list): | |
o = [] | |
i = 0 | |
added = set() | |
for item in j: | |
struct = json_structure(item) | |
dump = str(struct) | |
if dump in added: | |
continue | |
added.add(dump) | |
o.append((str(i), struct)) | |
elif isinstance(j, dict): | |
o = [] | |
for k in j: | |
o.append((k, json_structure(j[k]))) | |
else: | |
return type(j).__name__ | |
# sort by item[0] | |
o = sorted(o, key=lambda x: x[0]) | |
return o | |
def json_struc_modify(j): | |
struct = json_structure(j) | |
print(json.dumps(struct)) | |
json_struc_modify([{"a": 1}, {"a": 1}]) | |
# [["0", [["a", "int"]]]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment