Python基础(二十四、JSON和pyecharts)

文章目录

  • 一、JSON
    • 1.JSON介绍
    • 2.JSON格式数据转化
    • 3.示例
  • 二、pyecharts
    • 1.安装pyecharts包
    • 2.查看官方示例
  • 三、开发示例

一、JSON

1.JSON介绍

JSON是一种轻量级的数据交互格式,采用完全独立于编程语言的文本格式来存储和表示数据(就是字符串)。
Python语言使用JSON有很大优势,因为JSON无非就是一个单独的字典或一个内部元素都是字典的列表。
总结所以JSON可以直接和Python的字典或列表进行无缝转换。

2.JSON格式数据转化

通过 json.dumps(data) 方法把python数据转化为了json数据

data = json.dumps(data)

如果有中文可以带上:ensure ascii=False参数来确保中文正常转换
通过 json.loads(data) 方法把json数据转化为了 python列表或字典

data = json.loads(data)

3.示例

echarts/
	__init__.py
	data.txt
	jsonData.py

data.txt

{
  "code": 10000,
  "msg": null,
  "error": true,
  "data": {
    "total": 1664,
    "items": [
      {
        "stat_date": "2024-01-09",
        "genome": 1,
        "industrial": 3,
        "literature": 3,
        "patent": 6
      },
      {
        "stat_date": "2024-01-08",
        "genome": 3,
        "industrial": 8,
        "literature": 6,
        "patent": 9
      },
      {
        "stat_date": "2024-01-07",
        "genome": 3,
        "industrial": 5,
        "literature": 7,
        "patent": 6
      },
      {
        "stat_date": "2024-01-06",
        "genome": 5,
        "industrial": 7,
        "literature": 3,
        "patent": 8
      },
      {
        "stat_date": "2024-01-05",
        "genome": 9,
        "industrial": 7,
        "literature": 5,
        "patent": 7
      },
      {
        "stat_date": "2024-01-04",
        "genome": 3,
        "industrial": 5,
        "literature": 8,
        "patent": 5
      },
      {
        "stat_date": "2024-01-03",
        "genome": 8,
        "industrial": 0,
        "literature": 8,
        "patent": 6
      },
      {
        "stat_date": "2024-01-02",
        "genome": 0,
        "industrial": 9,
        "literature": 4,
        "patent": 4
      },
      {
        "stat_date": "2024-01-01",
        "genome": 7,
        "industrial": 8,
        "literature": 0,
        "patent": 3
      },
      {
        "stat_date": "2024-01-10",
        "genome": 3,
        "industrial": 7,
        "literature": 4,
        "patent": 6
      }
    ],
    "has_more": true
  }
}

jsonData.py

import json

def formatData():
    # 日期列表
    date_data = {}
    date = []
    # 数据
    genome_data = []
    industrial_data = []
    literature_data = []
    patent_data = []
    try:
        with open("D:/test/demo/echarts/data.txt","r",encoding="utf-8") as file:
            for line in file:
                line = line.strip()
                if len(line.split(":")) == 1:
                    continue
                data = line.split(":")[1].replace('"',"").strip(" ,")
                if line.startswith('"stat_date"'):
                    date.append(data)
                elif line.startswith('"genome"'):
                    genome_data.append(data)
                elif line.startswith('"industrial"'):
                    industrial_data.append(data)
                elif line.startswith('"literature"'):
                    literature_data.append(data)
                elif line.startswith('"patent"'):
                    patent_data.append(data)
    except Exception as e:
        print(f"出现异常啦:{e}")

    date_data["date"] = date
    date_json = json.dumps(date_data)
    genome_json = json.dumps(genome_data)
    industrial_json = json.dumps(industrial_data)
    literature_json = json.dumps(literature_data)
    patent_json = json.dumps(patent_data)
    
    print(f"{type(date_json)},{date_json}")
    print(f"{type(genome_json)},{genome_json}")
    print(f"{type(industrial_json)},{industrial_json}")
    print(f"{type(literature_json)},{literature_json}")
    print(f"{type(patent_json)},{patent_json}")
    return date_json,genome_json,industrial_json,literature_json,patent_json

输出:

,{"date": ["2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09", "2024-01-09"]}
,["1", "3", "3", "5", "9", "3", "8", "0", "7", "3"]
,["3", "8", "5", "7", "7", "5", "0", "9", "8", "7"]
,["3", "6", "7", "3", "5", "8", "8", "4", "0", "4"]
,["6", "9", "6", "8", "7", "5", "6", "4", "3", "6"]

二、pyecharts

开发可视化图表使用的技术栈是Echarts框架的python版本:pyecharts包。

1.安装pyecharts包

通过pip下载pyecharts包,在开发过程中直接引用即可。
下载命令如下:

pip install pyecharts

代码中引用示例:

import pyecharts.options as opts
from pyecharts.charts import Line

2.查看官方示例

pyecharts-gallery,可通过官方示例详细学习和使用。

三、开发示例

下面我们就是用上面的JSON和pyecharts进行实践,生成一个折线图,且带有工具栏。通过浏览器访问html文件可查看统计图。例如:
Python基础(二十四、JSON和pyecharts)_第1张图片
可通过工具栏中下载图片,切换柱状图,折线图,数据等。

代码示例如下:

echarts/
	__init__.py
	data.txt
	jsonData.py
	# 运行后生成line.html
	line.html
	line.py

jsonData.py代码不变
line.py

import json

import pyecharts.options as opts
from pyecharts.charts import Line
import jsonData

date_json,genome_json,industrial_json,literature_json,patent_json = jsonData.formatData()
date = json.loads(date_json)["date"]
(
    Line()
    .add_xaxis(xaxis_data=date)
    .add_yaxis(
        series_name="genome",
        y_axis=json.loads(genome_json),
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=True)
    )
    .add_yaxis(
        series_name="industrial",
        y_axis=json.loads(industrial_json),
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=True)
    )
    .add_yaxis(
        series_name="patent",
        y_axis=json.loads(patent_json),
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=True)
    )
    .add_yaxis(
        series_name="literature",
        y_axis=json.loads(literature_json),
        symbol="emptyCircle",
        is_symbol_show=True,
        label_opts=opts.LabelOpts(is_show=True)
    )
    .set_global_opts(
        title_opts=opts.TitleOpts(title="数统计", subtitle="纯属虚构"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(type_="category"),
        yaxis_opts=opts.AxisOpts(
            type_="value",
            splitline_opts=opts.SplitLineOpts(is_show=True),
        )
    )
    .render("D:/test/demo/echarts/line.html")
)

运行line.py之后生成line.html文件,直接浏览器打开,可以看到如图:
Python基础(二十四、JSON和pyecharts)_第2张图片

Python基础(二十四、JSON和pyecharts)_第3张图片

你可能感兴趣的:(python,python,json,echarts)