{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "5f4f41a4",
   "metadata": {},
   "source": [
    "# 模块json:处理JSON数据"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d242ce20",
   "metadata": {},
   "source": [
    "[JSON (JavaScript Object Notation)](https://www.json.org/json-zh.html)是一种轻量级的数据交换格式,易于人阅读和编写,同时也易于机器解析和生成。"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b54ba7b6",
   "metadata": {},
   "source": [
    "## JSON 基础\n",
    "\n",
    "JSON 的基础结构有两种:键值对 (name/value pairs) 和数组 (array)。\n",
    "\n",
    "JSON 具有以下形式:\n",
    "\n",
    "- object - 对象,用花括号表示,形式为(数据是无序的):\n",
    "    - { pair_1, pair_2, ..., pair_n }\n",
    "- pair - 键值对,形式为:\n",
    "    - string : value\n",
    "- array - 数组,用中括号表示,形式为(数据是有序的):\n",
    "    - [value_1, value_2, ..., value_n ]\n",
    "- value - 值,可以是\n",
    "    - string 字符串\n",
    "    - number 数字\n",
    "    - object 对象\n",
    "    - array 数组\n",
    "    - true / false / null 特殊值\n",
    "    - string 字符串\n",
    "    \n",
    "例子:\n",
    "```json\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",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "93548a76",
   "metadata": {},
   "source": [
    "## JSON 与 Python 的转换\n",
    "\n",
    "将上面的结构放入字符串:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "2898b6f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "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",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8adeb55d",
   "metadata": {},
   "source": [
    "使用json模块读取数据:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "e4c003d2",
   "metadata": {},
   "outputs": [],
   "source": [
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "7f2d0a5f",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = json.loads(info_string)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3dd3e420",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'echo',\n",
       " 'age': 24,\n",
       " 'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],\n",
       " 'ages for school': {'primary school': 6,\n",
       "  'middle school': 9,\n",
       "  'high school': 15,\n",
       "  'university': 18},\n",
       " 'hobby': ['sports', 'reading'],\n",
       " 'married': False}"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "6b7c5790",
   "metadata": {},
   "source": [
    "将这个对象转换为JSON字符串:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "d26f98ab",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\"\\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\"\n"
     ]
    }
   ],
   "source": [
    "print(json.dumps(info_string))"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "27db956b",
   "metadata": {},
   "source": [
    "## 读写JSON文件"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ca493b16",
   "metadata": {},
   "source": [
    "写JSON文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f82a0f60",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"info.json\", \"w\") as f:\n",
    "    json.dump(data, f)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8fe47130",
   "metadata": {},
   "source": [
    "查看文件内容:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "0a81396d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\"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}\n"
     ]
    }
   ],
   "source": [
    "with open(\"info.json\") as f:\n",
    "    print(f.read())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1e6daad4",
   "metadata": {},
   "source": [
    "读JSON文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "05fec9f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"info.json\") as f:\n",
    "    info = json.load(f)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "f8b762b1",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'name': 'echo',\n",
       " 'age': 24,\n",
       " 'coding skills': ['python', 'matlab', 'java', 'c', 'c++', 'ruby', 'scala'],\n",
       " 'ages for school': {'primary school': 6,\n",
       "  'middle school': 9,\n",
       "  'high school': 15,\n",
       "  'university': 18},\n",
       " 'hobby': ['sports', 'reading'],\n",
       " 'married': False}"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "info"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "99779d2b",
   "metadata": {},
   "source": [
    "删除临时文件:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "32ffb617",
   "metadata": {},
   "outputs": [],
   "source": [
    "%rm info.json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "b9fc168e",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}