JSON(full name: JavaScript Object Notation object notation) is a lightweight text data exchange format. The data format of JSON is actually the dictionary format in python , which can contain arrays enclosed in square brackets, which are lists in python.
JSON is language independent
JSON is self-descriptive and easier to understand
JSON than XML is smaller, faster, and easier to parse
Crawlers often obtain interface data, which is in JSON format
Grammar format:{key1:value1, key2:value2,}
Key-value pair format (separated by colon), use commas to connect the pairs
Simple case: JSON object
{ "name": "小明", "age": 18}
Complex case: JSON array
{ "student": [ {"name": "小明", "age": 11}, {"name": "小红","age": 10} ], "classroom": {"class1": "room1", "class2": "room2"}}
1. The key part of the key-value pair of json must be wrapped in double quotes"
, single quotes will not work (so if keywords appear in the key, they will also be characterized), and objects in js are not mandatory Requirements (so keywords are not allowed in the key).
2. The value part of the key-value pair of json is not allowed to have function, undefined, NaN, but it can have null, the value of the object in js can appear in.
3. After the json data ends, meaningless commas are not allowed to appear, such as:{"name":"admin","age":18,}
, Pay attention to the comma after 18 at the end of the data, which is not allowed.
The correct json format is as follows:
# 格式1:JSON 对象{"name": "admin", "age": 18}# 格式2:JSON 数组{ "student": [ {"name": "小明", "age": 18}, {"name": "小红", "age": 16}, {"name": "小黑", "age": 20} ]}
The wrong json format is as follows:
1. Use jsON string to generate python object (load)
2. Format the python object into ison string (dump)
Converts data fromPython to json
format. There will be changes in data type, as shown in the following table:
Python | JSON |
---|---|
object | |
array | |
string | |
number | |
true | |
false | |
null |
Python | |
---|---|
array | |
string | |
number(int) | |
number(real) | |
true | |
false | |
##null | |
3. Usage method |
将python数据类型转换为json格式的字符串。
语法格式:json.dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
>>> import json # Python字典 >>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True} >>> print(person) {'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True} >>> type(person)>> jsonStr = json.dumps(person) >>> print(jsonStr ) {"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true} >>> type(jsonStr)
从上可以看出json格式和Python格式的区别在于:python格式打印输出是单引号,类型为dict
。而json格式打印输出是双引号,类型为:str
。True
的开头大小写区别。
使用参数能让JSON字串格式化输出:
>>> print(json.dumps(person, sort_keys=True, indent=4, separators=(',', ': '))){ "age": 30, "isonly": true, "name": "\u5c0f\u660e", "tel": [ "888888", "1351111111" ]}
参数解读:
sort_keys
:是否排序
indent
:定义缩进距离
separators
:是一个元组,定义分隔符的类型
skipkeys
:是否允许JSON字串编码字典对象时,字典的key不是字符串类型(默认是不允许)
修改分割符类型:
>>> print(json.dumps(person, sort_keys=True, indent=4, separators=('!', '-'))){ "age"-30! "isonly"-true! "name"-"\u5c0f\u660e"! "tel"-[ "888888"! "1351111111" ]
文件操作:
import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}jsonStr = json.dumps(person)with open('test.json', 'w', encoding='utf-8') as f: # 打开文件 f.write(jsonStr) # 在文件里写入转成的json串
查看生成的新文件:
将python数据类型转换并保存到son格式的文件内。
语法格式:json.dump(obj, fp, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open('data.json', 'w'))
查看生成的新文件:
使用参数能让JSON字串格式化输出:
import json person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}json.dump(person, open('data.json', 'w'), sort_keys=True, indent=4, separators=(',', ': '))
再次查看文件:json.dumps
和json.dump
写入文件的区别:
dump() 不需要使用.write()
方法,只需要写那个字典,那个文件即可;而 dumps() 需要使用.write()
方法写入。
如果把字典写到文件里面的时候,dump()好用;但是如果不需要操作文件,或需要把内容存储到数据库何excel,则需要使用dumps()先把字典转换成字符串,再写入
将json格式的字符串转换为python的类型。
语法格式:json.loads(s, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
>>> import json# Python字典>>> person = {"name": "小明", "age": 30, "tel": ["888888", "1351111111"], "isonly": True}>>> print(person){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> type(person)>> jsonStr = json.dumps(person) >>> print(jsonStr ){"name": "\u5c0f\u660e", "age": 30, "tel": ["888888", "1351111111"], "isonly": true}>>> type(jsonStr) # json字符串再转换为Python字典>>> python_obj = json.loads(jsonStr)>>> print(python_obj){'name': '小明', 'age': 30, 'tel': ['888888', '1351111111'], 'isonly': True}>>> print(type(python_obj)) # 打印字典的所有key>>> print(python_obj.keys()) dict_keys(['name', 'age', 'tel', 'isonly']) # 打印字典的所有values>>> print(python_obj.values()) dict_values(['小明', 30, ['888888', '1351111111'], True])
文件操作:
import json f = open('data.json', encoding='utf-8')content = f.read() # 使用loads()方法需要先读文件 python_obj = json.loads(content)print(python_obj)
输出结果:
从json格式的文件中读取数据并转换为python的类型。
语法格式:json.load(fp, *, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
文件操作:
import json python_obj = json.load(open('data.json','r'))print(python_obj)print(type(python_obj))
输出结果:
json.load()
和json.loads()
区别:
loads() 传的是json字符串,而 load() 传的是文件对象
使用 loads() 时需要先读取文件在使用,而 load() 则不用
不管是dump还是load,带s的都是和字符串相关的,不带s的都是和文件相关的
记录工作中常用的一个小技巧
cmd控制台安装第三方模块:
pip install xmltodict
新建一个1.xml
文件:
tom mary love
转换代码实现:
import jsonimport xmltodictdef xml_to_json(xml_str): """parse是的xml解析器,参数需要 :param xml_str: xml字符串 :return: json字符串 """ xml_parse = xmltodict.parse(xml_str) # json库dumps()是将dict转化成json格式,loads()是将json转化成dict格式。 # dumps()方法的ident=1,格式化json json_str = json.dumps(xml_parse, indent=1) return json_str XML_PATH = './1.xml' # xml文件的路径with open(XML_PATH, 'r') as f: xmlfile = f.read() with open(XML_PATH[:-3] + 'json', 'w') as newfile: newfile.write(xml_to_json(xmlfile))
输出结果(生成json文件):
新建test.json
文件:
{ "student": { "course": { "name": "math", "score": "90" }, "info": { "sex": "male", "name": "name" }, "stid": "10213" }}
转换代码实现:
import xmltodictimport jsondef json_to_xml(python_dict): """xmltodict库的unparse()json转xml :param python_dict: python的字典对象 :return: xml字符串 """ xml_str = xmltodict.unparse(python_dict) return xml_str JSON_PATH = './test.json' # json文件的路径with open(JSON_PATH, 'r') as f: jsonfile = f.read() python_dict = json.loads(jsonfile) # 将json字符串转换为python字典对象 with open(JSON_PATH[:-4] + 'xml', 'w') as newfile: newfile.write(json_to_xml(python_dict))
输出结果(生成xml文件):
The above is the detailed content of How to use Python's json standard library. For more information, please follow other related articles on the PHP Chinese website!
|
json.dump(obj, fp) |
|
json.loads(s) |
|
json.load(fp) |
|