本文最后更新于 271 天前,其中的信息可能已经过时,如有错误请发送邮件到wuxianglongblog@163.com
模块json:处理JSON数据
JSON (JavaScript Object Notation)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。
JSON 基础
JSON 的基础结构有两种:键值对 (name/value pairs) 和数组 (array)。
JSON 具有以下形式:
- object - 对象,用花括号表示,形式为(数据是无序的):
- { pair_1, pair_2, ..., pair_n }
- pair - 键值对,形式为:
- string : value
- array - 数组,用中括号表示,形式为(数据是有序的):
- [value_1, value_2, ..., value_n ]
- value - 值,可以是
- string 字符串
- number 数字
- object 对象
- array 数组
- true / false / null 特殊值
- string 字符串
例子:
{
"name": "echo",
"age": 24,
"coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"],
"ages for school": {
"primary school": 6,
"middle school": 9,
"high school": 15,
"university": 18
},
"hobby": ["sports", "reading"],
"married": false
}
JSON 与 Python 的转换
将上面的结构放入字符串:
info_string = """
{
"name": "echo",
"age": 24,
"coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"],
"ages for school": {
"primary school": 6,
"middle school": 9,
"high school": 15,
"university": 18
},
"hobby": ["sports", "reading"],
"married": false
}
"""
使用json模块读取数据:
import json
data = json.loads(info_string)
data
{'name': 'echo',
'age': 24,
'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],
'ages for school': {'primary school': 6,
'middle school': 9,
'high school': 15,
'university': 18},
'hobby': ['sports', 'reading'],
'married': False}
将这个对象转换为JSON字符串:
print(json.dumps(info_string))
"\n{\n \"name\": \"echo\",\n \"age\": 24,\n \"coding skills\": [\"python\", \"matlab\", \"java\", \"c\", \"c++\", \"ruby\", \"scala\"],\n \"ages for school\": { \n \"primary school\": 6,\n \"middle school\": 9,\n \"high school\": 15,\n \"university\": 18\n },\n \"hobby\": [\"sports\", \"reading\"],\n \"married\": false\n}\n"
读写JSON文件
写JSON文件:
with open("info.json", "w") as f:
json.dump(data, f)
查看文件内容:
with open("info.json") as f:
print(f.read())
{"name": "echo", "age": 24, "coding skills": ["python", "matlab", "java", "c", "c++", "ruby", "scala"], "ages for school": {"primary school": 6, "middle school": 9, "high school": 15, "university": 18}, "hobby": ["sports", "reading"], "married": false}
读JSON文件:
with open("info.json") as f:
info = json.load(f)
info
{'name': 'echo',
'age': 24,
'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],
'ages for school': {'primary school': 6,
'middle school': 9,
'high school': 15,
'university': 18},
'hobby': ['sports', 'reading'],
'married': False}
删除临时文件:
%rm info.json