#!/usr/bin/env python # coding: utf-8 # # 模块json:处理JSON数据 # [JSON (JavaScript Object Notation)](https://www.json.org/json-zh.html)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。 # ## 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 字符串 # # 例子: # ```json # { # "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 的转换 # # 将上面的结构放入字符串: # In[1]: 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模块读取数据: # In[2]: import json # In[3]: data = json.loads(info_string) # In[4]: data # 将这个对象转换为JSON字符串: # In[5]: print(json.dumps(info_string)) # ## 读写JSON文件 # 写JSON文件: # In[6]: with open("info.json", "w") as f: json.dump(data, f) # 查看文件内容: # In[7]: with open("info.json") as f: print(f.read()) # 读JSON文件: # In[8]: with open("info.json") as f: info = json.load(f) # In[9]: info # 删除临时文件: # In[10]: get_ipython().run_line_magic('rm', 'info.json') # In[ ]: