import json
"""将python的字典和列表转化为json字符串。json是前后端交互的枢纽"""
dic = {'name': '莉莉', 'age':18}
str_json = json.dumps(dic, ensure_ascii=False) # 将python中的字典转换为json字符串
print(str_json)
print(type(str_json))
lst = ["苹果", "桃子", "梨子"]
str2_json = json.dumps(lst, ensure_ascii=False) # 将python中的列表转化为json字符串
print(str2_json)
print(type(str2_json))
{"name": "莉莉", "age": 18}
<class 'str'>
["苹果", "桃子", "梨子"]
<class 'str'>
import json
"""将json字符串转化为Python的数据类型"""
str_json = '{"name": "莉莉", "age": 18}'
dic = json.loads(str_json) # 安全
print(dic)
print(type(dic))
print(eval(str_json)) # 不安全
str2_json = '["苹果", "桃子", "梨子"]'
lst = json.loads(str2_json)
print(lst)
print(type(lst))
{'name': '莉莉', 'age': 18}
<class 'dict'>
{'name': '莉莉', 'age': 18}
['苹果', '桃子', '梨子']
<class 'list'>
import json
# 将dict字典类型数据转换为json字符串
dic = {"name": "莉莉", "age": 18}
json_str = json.dumps(dic, ensure_ascii=False)
print(json_str)
print(type(json_str))
# 将json字符串转换为dict字典类型
json_str = '{"name": "lily", "age": 18}'
dic = json.loads(json_str)
print(dic)
print(type(dic))
{"name": "莉莉", "age": 18}
<class 'str'>
{'name': 'lily', 'age': 18}
<class 'dict'>
import json
# 将list类型数据转换为json字符串
dic = ["莉莉", 18]
json_str = json.dumps(dic, ensure_ascii=False)
print(json_str)
print(type(json_str))
# 将json字符串转换为list类型
json_str = '["莉莉", 18]'
dic = json.loads(json_str)
print(dic)
print(type(dic))
["莉莉", 18]
<class 'str'>
['莉莉', 18]
<class 'list'>
import json
# 将tuple类型数据转换为json字符串
dic = ("莉莉", 18)
json_str = json.dumps(dic, ensure_ascii=False)
print(json_str)
print(type(json_str))
# 将json字符串转换为list类型
json_str = '["莉莉", 18]'
dic = json.loads(json_str)
print(dic)
print(type(dic))
["莉莉", 18]
<class 'str'>
['莉莉', 18]
<class 'list'>
import json
# 将set类型数据不能转换为json字符串
dic = {"莉莉", 18}
json_str = json.dumps(dic, ensure_ascii=False)
print(json_str)
print(type(json_str))
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-72-62a9e6cbaec2> in <module>()
3 # 将set类型数据不能转换为json字符串
4 dic = {"莉莉", 18}
----> 5 json_str = json.dumps(dic, ensure_ascii=False)
6 print(json_str)
7 print(type(json_str))
~Anaconda3libjson\__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
236 check_circular=check_circular, allow_nan=allow_nan, indent=indent,
237 separators=separators, default=default, sort_keys=sort_keys,
--> 238 **kw).encode(obj)
239
240
~Anaconda3libjsonencoder.py in encode(self, o)
197 # exceptions aren't as detailed. The list call should be roughly
198 # equivalent to the PySequence_Fast that ''.join() would do.
--> 199 chunks = self.iterencode(o, _one_shot=True)
200 if not isinstance(chunks, (list, tuple)):
201 chunks = list(chunks)
~Anaconda3libjsonencoder.py in iterencode(self, o, _one_shot)
255 self.key_separator, self.item_separator, self.sort_keys,
256 self.skipkeys, _one_shot)
--> 257 return _iterencode(o, 0)
258
259 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
~Anaconda3libjsonencoder.py in default(self, o)
178 """
179 raise TypeError("Object of type '%s' is not JSON serializable" %
--> 180 o.__class__.__name__)
181
182 def encode(self, o):
TypeError: Object of type 'set' is not JSON serializable
import json
"""将Python的数据类型dict或list转换为json字符串,并写入文件中"""
dic = {'name': '莉莉', 'age':18}
json.dump(dic, open("user.json", "w"), ensure_ascii=False)
lst = ["苹果", "桃子", "梨子"]
json.dump(lst, open("fruit.json", "w"), ensure_ascii=False)
import json
"""读取文件中的json字符串"""
dic = json.load(open("user.json", "r"))
print(dic)
print(type(dic))
lst = json.load(open("fruit.json", "r"))
print(lst)
print(type(lst))
{'name': '莉莉', 'age': 18}
<class 'dict'>
['苹果', '桃子', '梨子']
<class 'list'>
import json
"""前端json和python字典、列表的区别:前端true, false, null,双引号 ==》对应python的True, False, None, 单引号"""
lst = [True, False, None, '引号']
print(json.dumps(lst, ensure_ascii=False))
[true, false, null, "引号"]