一、图解
json.loads():解析一个有效的JSON字符串并将其转换为Python字典
json.load():从一个文件读取JSON类型的数据,然后转转换成Python字典
二、json.loads()用法
1、例子
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import json data = { "name" : "Satyam kumar" , "place" : "patna" , "skills" : [ "Raspberry pi" , "Machine Learning" , "Web Development" ], "email" : "xyz@gmail.com" , "projects" : [ "Python Data Mining" , "Python Data Science" ] } with open ( "data_file.json" , "w" ) as write: json.dump(data, write) with open ( "data_file.json" , "r" ) as read_content: print (json.load(read_content)) |
2、Python和Json数据类型的映射
JSON Equivalent | Python |
---|---|
object | dict |
array | list |
string | str |
number | int |
true | True |
false | False |
null | None |
三、json.load()用法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import json # JSON string: # Multi-line string data = """{ "Name": "Jennifer Smith", "Contact Number": 7867567898, "Email": "jen123@gmail.com", "Hobbies":["Reading", "Sketching", "Horse Riding"] }""" # parse data: res = json.loads(data) # the result is a Python dictionary: print (res) |
四、此外还有一种json.dumps
json.dumps 用于将 Python 对象编码成 JSON 字符串。
语法
1
|
json.dumps(obj, skipkeys = False , ensure_ascii = True , check_circular = True , allow_nan = True , cls = None , indent = None , separators = None , encoding = "utf-8" , default = None , sort_keys = False , * * kw) |
实例
以下实例将数组编码为 JSON 格式数据:
1
2
3
4
5
6
7
|
#!/usr/bin/python import json data = [ { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 } ] data2 = json.dumps(data) print (data2) |
以上代码执行结果为:
1
|
[{ "a" : 1 , "c" : 3 , "b" : 2 , "e" : 5 , "d" : 4 }] |
使用参数让 JSON 数据格式化输出:
1
2
3
4
5
6
7
|
#!/usr/bin/python import json data = [ { 'a' : 1 , 'b' : 2 , 'c' : 3 , 'd' : 4 , 'e' : 5 } ] data2 = json.dumps({ 'a' : 'Runoob' , 'b' : 7 }, sort_keys = True , indent = 4 , separators = ( ',' , ': ' )) print (data2) |
以上代码执行结果为:
1
2
3
4
|
{ "a" : "Runoob" , "b" : 7 } |
以上就是Python中json.load()和json.loads()有哪些区别的详细内容,更多关于Python中json.load()和json.loads()的资料请关注服务器之家其它相关文章!
原文链接:https://www.cnblogs.com/lemon-le/p/14812538.html