使用json.dumps的目的是将python对象转化为字符串,再用json.loads转化为python对象
s = str([1,2]) print(s) s = json.dumps([1,2]) print(s) t = json.dumps([1, 2]) == str([1, 2]) print(t) """ [1, 2] [1, 2] True """
# str转化后的字符串中,引号是用单引号,而json.dumps是双引号,这在字典和列表中都是这样 s = str(['a', 'b']) print(s) s = json.dumps(['a', 'b']) print(s) t = json.dumps(['a', 'b']) == str(['a', 'b']) print(t) """ ['a', 'b'] ["a", "b"] False """ s = str({'a': 1}) print(s) s = json.dumps({'a': 1}) print(s) t = json.dumps({'a': 1}) == str({'a': 1}) print(t) """ {'a': 1} {"a": 1} False """
# str转化后的字符串中,True是首字母大写的,而json.dumps将所有字母都转化为了小写 s = str([True, False]) print(s) s = json.dumps([True, False]) print(s) t = json.dumps([True, False]) == str([True, False]) print(t) """ [True, False] [true, false] False """
# None:str转化后的字符串中,None还是用None表示,而json.dumps则用null表示 s = str([1, None]) print(s) s = json.dumps([1, None]) print(s) t = json.dumps([1, None]) == str([1, None]) print(t) """ [1, None] [1, null] False """
那么 json格式的str 使用dumps会是怎么样呢?
data = '{"A": "a", "B": 1, "C": null}' a = json.loads(data) print(a) print(type(a)) """ {'A': 'a', 'B': 1, 'C': None} <class 'dict'> """
data = '{"A": "a", "B": 1, "C": null}' a = json.dumps(data) print(a) print(type(a)) a = json.loads(a) print(a) print(type(a)) a = json.loads(a) print(a) print(type(a)) """ "{\"A\": \"a\", \"B\": 1, \"C\": null}" <class 'str'> {"A": "a", "B": 1, "C": null} <class 'str'> {'A': 'a', 'B': 1, 'C': None} <class 'dict'> """
# str + str --> dict data = '{"A": "B", "C": ${arg1}$, "D": null}' arg = '{"aa": "11", "bb": "22"}' data = re.sub(r'\${(.*?)}\$', str(arg), str(data), count=1) l1 = json.loads(data) print(l1) print(type(l1)) """ {'A': 'B', 'C': {'aa': '11', 'bb': '22'}, 'D': None} <class 'dict'> """
# str + 对象dumps --> dict data = '{"A": "B", "C": ${arg1}$, "D": null}' arg = {"aa": "11", "bb": "22"} arg = json.dumps(arg, ensure_ascii=False) data = re.sub(r'\${(.*?)}\$', arg, data, count=1) l2 = json.loads(data) print(l2) print(type(l2)) """ {'A': 'B', 'C': {'aa': '11', 'bb': '22'}, 'D': None} <class 'dict'> """
# str + (str->dumps) --> dict data = '{"A": "B", "C": "${arg1}$", "D": null}' arg = "hello" data = json.dumps(data, ensure_ascii=False) data = re.sub(r'\${(.*?)}\$', arg, data, count=1) l2 = json.loads(data) print(type(l2)) l2 = json.loads(l2) print(l2) print(type(l2)) """ <class 'str'> {'A': 'B', 'C': 'hello', 'D': None} <class 'dict'> """
参考:https://juejin.cn/post/6844903609499385869